select2显示未更新标签文本,但值正在更改 [英] select2 display not updating label text but value is changing

查看:105
本文介绍了select2显示未更新标签文本,但值正在更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 select2 v4.0.3 与JQuery一起使用. 我将选择器初始化为:

I am using select2 v4.0.3 along with JQuery. I initialize my selectors as:

$("#datatype").select2({
        theme: "classic"
        }); 

 $("#unit").select2({
        theme: "classic"
        }); 

然后我要检测#datatype上的更改并更改#unit的值,如下所示:

Then I want to detect a change on #datatype and change the value of #unit which I do as follows:

$("#datatype").on('select2:select',function () {
    $("#unit").val('21'); //udpate unit type to be 'none'
    });

问题在于#unit的值已设置为21,但该选择器的显示标签未更新.有什么建议吗?

The problem is that the value of #unit is getting set to 21 but the displayed label for that selector is not updating. Any suggestions ?

似乎select2不知道该事件,或者似乎尚未正确设置它以侦听更改.我不确定解决方案是什么.我是Web技术的新手.

It seems as if select2 is not aware of the event or that it has not been setup properly to listen to changes. I am not sure what the solution is. I am new to web technologies.

推荐答案

在仔细阅读Select2文档之后,所有.val()更新都必须紧跟$('#unit').trigger('change');

After digging through the Select2 documentation, any .val() updates need to be followed by $('#unit').trigger('change');

因此,在我的情况下,代码应类似于

So in my case, the code should look like

$("#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及更高版本.

Note that this is only true for select2 version 4 and greater.

我还建议人们升级到版本4,因为您可以直接调用更改值而无需指定initSelect()

I would also recommend people upgrade to version 4 since you can make direct calls to change values without having to specify initSelect()

这篇关于select2显示未更新标签文本,但值正在更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆