Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 596
Kingsley Simon Avatar asked Dec 11 '22 20:12

Kingsley Simon


1 Answers

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

like image 69
Yevgeniy Afanasyev Avatar answered Dec 28 '22 11:12

Yevgeniy Afanasyev