Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select2 display not updating label text but value is changing

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.

like image 389
marc Avatar asked Jul 23 '16 03:07

marc


People also ask

How do I set Select2 values?

To dynamically set the "selected" value of a Select2 component: $('#inputID'). select2('data', {id: 100, a_key: 'Lorem Ipsum'}); Where the second parameter is an object with expected values.

How do I create a Select2 dynamically?

HTML. Create a <select class="select2_el" > element to initialize select2 on page load and create <div id="elements" > container to store <select > element on button click using jQuery AJAX.

How do you add new option if not exist in the list using Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2').

What does Select2 () do?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.


1 Answers

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()

like image 163
marc Avatar answered Sep 19 '22 18:09

marc