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.
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.
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.
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').
Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With