Kingsley Simon
Kingsley Simon

Reputation: 2210

set select2 option using text not value

I know if i have a select2 and i want to set one of the options, i can do run this code.

 $(document).ready(function(){
     $('#btn').change(function(){
       $('#select').val(4).trigger("change")
     });    
 });

Lets say i want to get the text of the option

<option value=4>California</option>

but if i want to set it based on the text not the value, how do i do it?

I tried doing

$("#select").select2(data.text(), "California");

but it didnt work.

How can i do this programatically in jquery or javascript.

Any help is appreciated

Upvotes: 4

Views: 18845

Answers (4)

Yevgeniy Afanasyev
Yevgeniy Afanasyev

Reputation: 41290

For example: If you need to find Australia among other countries

let long_name = 'Australia';
let $element = $('.country-js')
let val = $element.find("option:contains('"+long_name+"')").val()
$element.val(val).trigger('change.select2');

Other answers did not work for me, probably because I use newer version of select2

Upvotes: 11

bob
bob

Reputation: 625

In addition for multi selects use this, for not losing already selected values

var selected=$("#foo option:selected").map(function(){ return this.value }).get();
selected.push( $("#foo option:contains('text')").val() );
$("#foo").val(selected).trigger('change');

Upvotes: 3

dsuelzle
dsuelzle

Reputation: 33

Further to Shakeel Ahmed's answer, you should call .trigger('change'), so in total something like this:

$("#select").select2("val", $("#select option:contains('Text')").val()).trigger('change');

Upvotes: 2

Shakeel Ahmed
Shakeel Ahmed

Reputation: 1848

You can use following codes

$("#select").select2("val", $("#select option:contains('Text')").val() );

If will select option using your Text

Upvotes: 1

Related Questions