Santhucool Santhucool - 5 months ago 17
Javascript Question

Make dropdown selected using option text (not using value) in select2

I have dropdown using select2 as follows:

<select class=".select2" id="sel">
<option value="1">Some Text</option>
<option value="2">Other Text</option>
<option value="3">best Text</option>
</select>


What I need to make default selection as a particular option , suppose it is second option so I do as follows:

$("#sel").select2("val","2");


It is working fine. What I need is I want to make the option selected only by using the text value, ie, something like that

$("#sel").select2("text","Other Text");


please check fiddle: FIDDLE

Please guide me how can I achieve this without using value and only text of option?

Answer

To trigger a change in value, append .trigger("change") to your script as below.

JSFIDDLE DEMO

$("#sel option:contains(Other Text)").attr('selected', true).trigger("change");