select2显示不更新标签文本但值正在变化

时间:2016-07-23 03:17:46

标签: jquery-select2 select2 jquery-select2-4

我正在使用 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不知道该事件或者它没有正确设置来监听更改。我不确定解决方案是什么。我是网络技术的新手。

2 个答案:

答案 0 :(得分:2)

在深入了解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()

答案 1 :(得分:0)

在select2 v4.0中,您还可以触发change.select2事件以更新显示的标签。这样可以防止其他正在监听更改事件的组件引起副作用。

$("#datatype").on('select2:select',function () {
    $('#unit').val('21'); // Select the option with a value of '21'
    $('#unit').trigger('change.select2'); // Notify only Select2 of changes
});
相关问题