Santhucool Santhucool - 3 months ago 13x
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>

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


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?


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


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