TOMSELECT

Lấy giá trị của Tomselect

Sau khi đã cấu hình tomselect cho một <select> sử dụng các hàm có sẵn để lấy giá trị và gắn giá trị cho tomselect.

Cú pháp

Để lấy giá trị của một tomselect ta dùng câu lệnh sau

Hàm sau sẽ trả về giá trị của thẻ <select>. Nếu có thể chọn nhiều giá trị bằng thẻ <select> (ví dụ <select multiple> ), thì hàm này trả về một mảng.

$("selector")[0].tomselect.getValue()

Ví dụ

               let inputval = $(".cbDanToc")[0].tomselect.getValue()
    $(".input_dantocval").val(inputval);

Đặt giá trị cho Tomselect

Để đặt giá trị mặc định cho một thẻ <select> ta dùng câu lệnh sau.

Cú pháp

$("selector")[0].tomselect.setValue(value)

Tham số: value Là giá trị mà bạn muốn hiển thị

Ví dụ

               $("select[name=Dm_DanToc]")[0].tomselect.setValue(1)

Lấy tất cả giá trị của tomselect

Để lấy tất cả giá trị của tomselect ta sử dụng câu lệnh.

Cú pháp

Object.keys($("selector")[0].tomselect.setValue(value))

Hoặc bạn có thể lấy tất cả thông tin từ tomselect bằng cú pháp.

Object.values($("selector")[0].tomselect.setValue(value))

Ví dụ

       let val = Object.keys($("select[name=Dm_DanToc]")[0].tomselect.options)
    $(".cbDanToc_Value").val(val)
       let val = Object.values($("select[name=Dm_DanToc]")[0].tomselect.options)
    $(".Dm_DanToc_text").text(JSON.stringify(val, null, 2))

Xóa giá trị cho Tomselect

Để xóa giá trị đang hiển thị cho một thẻ <select> ta dùng câu lệnh sau.

Cú pháp

$("selector")[0].tomselect.clear()

Hoặc bạn có thể xóa tất cả giá trị của một thẻ <select> bằng câu lệnh

$("selector")[0].tomselect.clearOptions()

Lưu ý lệnh này không xóa được giá trị đang hiển thị ở thẻ <select> mà phải dùng lệnh clear để xóa riêng.

Lưu ý lệnh này sẽ xóa hết tất cả lựa chọn của thể <select>.

Ví dụ

               $("select[name=dantoc_clear]")[0].tomselect.clear();
               $("select[name=dantoc_clearOption]")[0].tomselect.clearOptions();

Thêm giá trị cho Tomselect

Để thêm giá trị cho một thẻ <select> ta dùng câu lệnh sau.

Cú pháp

$("selector")[0].tomselect.addOption(data)

Tham số: data là một giá trị cần thêm vào dưới dạng object

Hoặc bạn có thể thêm một danh sách các giá trị của một thẻ <select> bằng câu lệnh

$("selector")[0].tomselect.addOptions(list[data])/p>

Tham số: list[data] là một danh sách các giá trị cần thêm vào dưới dạng object

Ví dụ

               $("select[name=dantoc_addOption]")[0].tomselect.addOption({id: 1001, ten: "DT Mới"});
    $("select[name=dantoc_addOption]")[0].tomselect.setValue(1001);
        let data = [{id: 1001, ten: "DT Mới"}, {id: 1002, ten: "DT mới 2"}]      
     $("select[name=dantoc_addOptions]")[0].tomselect.addOptions(data);
      $("select[name=dantoc_addOptions]")[0].tomselect.setValue(1001);