select2显示未更新标签文本,但值正在更改

编程入门 行业动态 更新时间:2024-10-11 07:35:37
本文介绍了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显示未更新标签文本,但值正在更改

本文发布于:2023-08-06 14:39:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1313028.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   标签

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!