【问题标题】:select2 display not updating label text but value is changingselect2 显示不更新标签文本但值正在更改
【发布时间】:2016-11-27 00:39:22
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    在翻阅 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()

    【讨论】:

      【解决方案2】:

      使用 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
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        相关资源
        最近更新 更多