netdjw
netdjw

Reputation: 6007

How to update select2 dropdown selected value based on a HTML select field

I'm using select2 jQuery plugin to make fancy my select boxes. If I update the base select field by jQuery the select2 item does not updated. Is there any way to the select2 to listen the original select field changes and then update itself?

Here is my HTML code:

<select name="myselect" id="myselect">
    <option value=""></option>
    <option value="a">A</option>
    <option value="b">B</option>
</select>

Default the first option (the empty one) will be selected. And here is my jQuery code:

$('select').select2();   // this line is running first always
                         // and there is no way to change the order

$('#myselect').val('a'); // this line is run after select2 built
                         // his elements

Is there any way to update the select2 element automatically?

Upvotes: 0

Views: 2883

Answers (2)

Ismail Arafath
Ismail Arafath

Reputation: 1

setTimeout(() => {
  $('#projectId').val(x.projectId.toString()).trigger('change');
  $('#itemType').val(x.itemType.toString()).trigger('change');
}, 10);

Upvotes: -1

netdjw
netdjw

Reputation: 6007

Found the solution (just the documentation not call it "update"):

$('#myselect').val('a').trigger('change');

Upvotes: 0

Related Questions