select2 display not updating label text but value is changing

北战南征 提交于 2020-01-04 06:15:13

问题


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

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

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

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'
    });

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 ?

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.


回答1:


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

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

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




回答2:


In select2 v4.0 you can also trigger the change.select2 event to update the displayed label. This prevents other components that are listening to the change event from causing side effects.

$("#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
});


来源:https://stackoverflow.com/questions/38537795/select2-display-not-updating-label-text-but-value-is-changing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!