Ajax响应后无法设置TomSelect选中值 求解决方案
解决TomSelect在Ajax响应后无法设置选中值的问题
TomSelect不能直接用jQuery的val()方法设置选中值,因为它有自己的API来管理组件内部状态。你需要通过实例化后的TomSelect对象调用setValue()方法来完成这个操作。
解决方案步骤:
- 确保你创建的TomSelect实例
hmb_peg在Ajax回调函数的作用域内可访问(当前代码的作用域已满足,可直接使用) - 在Ajax的
success回调中,替换原有的jQuery操作,改用TomSelect的专属方法
修改后的Ajax代码:
$(document).on('click','#btneditpgw',function(){ var id = $(this).attr('data-id'); $.ajax({ url : "/pegawaidetails/" + id, type: "GET", dataType: "JSON", success: function(data) { // 使用TomSelect实例的setValue方法设置选中值 hmb_peg.setValue(data.hmb_id); // 若需要触发组件的change事件,可传入第二个参数true // hmb_peg.setValue(data.hmb_id, true); $('#modal-editpegawai').modal('show'); }, error: function (jqXHR, textStatus, errorThrown) { console.log(jqXHR); alert('Error get data from ajax'); } }); });
补充说明:
setValue(value):支持传入单个值(单选场景)或数组(多选场景),用于设置组件的选中项- 第二个参数
triggerChange设为true时,会主动触发组件的change事件,和你原来的.change()作用一致 - 若遇到实例访问不到的情况,可通过
TomSelect.getInstance('#homebasepeg')直接获取组件实例:TomSelect.getInstance('#homebasepeg').setValue(data.hmb_id);
内容的提问来源于stack exchange,提问作者Habibi
相关产品推荐
相关产品推荐

