Reputation: 2210
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
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
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
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
Reputation: 1848
You can use following codes
$("#select").select2("val", $("#select option:contains('Text')").val() );
If will select option using your Text
Upvotes: 1