我正在将 select2 v4.0.3 与JQuery一起使用。
我将选择器初始化为:
$("#datatype").select2({
theme: "classic"
});
$("#unit").select2({
theme: "classic"
});
然后,我想检测
#datatype
的变化并更改#unit
的值,如下所示:$("#datatype").on('select2:select',function () {
$("#unit").val('21'); //udpate unit type to be 'none'
});
问题在于
#unit
的值已设置为21,但该选择器的显示标签未更新。有什么建议么 ?似乎select2不知道该事件,或者它尚未正确设置以监听更改。我不确定解决方案是什么。我是Web技术的新手。
最佳答案
在仔细阅读了Select2文档之后,所有.val()
更新都需要跟着$('#unit').trigger('change');
所以在我的情况下,代码应该看起来像
$("#datatype").on('select2:select',function () {
$('#unit').val('21'); // Select the option with a value of '21'
$('#unit').trigger('change'); // Notify any JS components that the value changed
});
请注意,这仅适用于select2版本4及更高版本。
我还建议人们升级到版本4,因为您可以直接调用更改值而不必指定
initSelect()
关于jquery-select2 - select2显示未更新标签文本,但值正在更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38537795/