Javacadabra
Javacadabra

Reputation: 5758

Finding text in Dropdown menu with Jquery and setting it to Selected

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

Answers (5)

getty_advaanz
getty_advaanz

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

Michelangelo
Michelangelo

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

K K
K K

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

Rohan Kumar
Rohan Kumar

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');
}

Demo

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

Javacadabra
Javacadabra

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

Related Questions