Reputation: 5758
I'm trying to check if a particular text value exists within a dropdown
menu and if it does I would like to set it's attribute to selected
.
I've managed to write an if
statement that checks to see if the text exists:
var country = usr.location;
if ($('select[name="country"] option:contains(' + country + ')').length) {
$(this).find('option:contains("' + country + '")').attr('selected', 'selected');
}
However, the issue I've run into is targeting the option
and setting it to selected
.
This is a fiddle of my work so far:
http://jsfiddle.net/javacadabra/ha2qwph3/
any help is appreciated.
EDIT: I've answered my own question but I'd be open to suggestions on ways in which my code could be improved. thank you.
Upvotes: 0
Views: 45
Reputation: 31
Please replace the below code
$(this).find('option:contains(' + country + ')').attr('selected', 'selected');
with
$('select option:contains(' + country + ')').attr('selected', 'selected');
Hope this helps you.Thank you.
Upvotes: 0
Reputation: 5948
You can dynamically add a country to a variable on change and then check for the existence, fix : http://jsfiddle.net/ha2qwph3/4/
$('#select').change(function(){
var country = $( "select option:selected" ).html();
if($('select[name="country"] option:contains(' + country + ')').length){
alert('found ' + country);
}
});
Upvotes: 0
Reputation: 18099
You can try this too: Demo
JS:
var country = "Ireland";
$('select[name="country"] option').each(function(){
if($(this).text().indexOf(country)>-1){
$(this).attr('selected','selected');
}
})
Upvotes: 1
Reputation: 40639
Correct way is,
You have no scope for this
in if-else
condition
var country = "Ireland";
if($('select[name="country"] option:contains(' + country + ')').length){
//alert('found ' + country);
$('select[name="country"] option:contains(' + country + ')').attr('selected', 'selected');
}
Even a better solution to make a cache of your select element
like,
var country = "Ireland";
var $countrySelected=$('select[name="country"] option:contains(' + country + ')');
if($countrySelected.length){
//alert('found ' + country);
$countrySelected.attr('selected', 'selected');
}
Upvotes: 1
Reputation: 5758
Actually, I've managed to find a solution myself after tinkering with the Fiddle. Here is the Code for anyone who may need to achieve the same thing:
var country = "Ireland";
if($('select[name="country"] option:contains(' + country + ')').length){
alert('found ' + country);
$('select[name="country"] option:contains(' + country + ')').attr('selected', 'selected');
}
Upvotes: 0