TomSelect set selected value on ajax response

1k views Asked by At

I have problem to set value on TomSelect with ajax response, usually I use $('#homebasepeg').val(data.hmb_id).change(); on general dropdown,

but when I apply it on TomSelect, it doesn't work, here is my TomSelect Code :

let hmb_peg = new TomSelect("#homebasepeg", {
    copyClassesToDropdown: false,
    dropdownClass: 'dropdown-menu ts-dropdown',
    optionClass:'dropdown-item',
    controlInput: '<input>',
    render:{
        item: function(data,escape) {
            if( data.customProperties ){
            return '<div><span class="dropdown-item-indicator">' + data.customProperties + '</span>' + escape(data.text) + '</div>';
        }
        return '<div>' + escape(data.text) + '</div>';
        },
        option: function(data,escape){
            if( data.customProperties ){
        return '<div><span class="dropdown-item-indicator">' + data.customProperties + '</span>' + escape(data.text) + '</div>';
                    }
        return '<div>' + escape(data.text) + '</div>';
        },
    },
});

and here is my ajax code :

$(document).on('click','#btneditpgw',function(){ 
 var id = $(this).attr('data-id');
 $.ajax({
       url : "/pegawaidetails/" + id,
       type: "GET",
       dataType: "JSON",
       success: function(data)
       {
            
         $('#homebasepeg').val(data.hmb_id).change();             
         
         $('#modal-editpegawai').modal('show');
       },
        error: function (jqXHR, textStatus, errorThrown)
      {
        console.log(jqXHR);
        alert('Error get data from ajax');
      }
   });
});

Please help me to solve this problem!

1

There are 1 answers

0
Habibi On

I already solved my problem with this code :

var options_homebase = [data].map(function(item) {
   return { value: item.hmb_id, text: item.hmb_name };
});
hmb_peg.addOption(options_homebase);
var selectedValue_hmb = { value: data.hmb_id, text: data.hmb_name };
hmb_peg.setValue(selectedValue_hmb.value);

Thank you for responding my question.