Santhucool Santhucool - 1 year ago 81
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?

Answer Source

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download