Skip to content Skip to sidebar Skip to footer

Add The "selected" Attribute To A Drop Down Option With Jquery

How do I add the attribute 'selected' to a drop down menu option based on that option matching some variable? Here is how the dropdown is populated... loginOptions = ['First', 'Sec

Solution 1:

I'd use .val() at the end of your method, this sets based on value, like this:

$('#Login').val(existingLoginValue);

Similarly, to get the value, call it without any parameters like this:

var currentValue = $('#Login').val();

Solution 2:

If you only want to do one value then yeah, the val() works. Otherwise, you can also do this:

$option=$('<option value="'+ loginOptions[i] +'">'+ loginOptions[i]+'</option>').appendTo(Login);
if (loginOptions[i] == existingLoginValue) {
    $option.attr('selected',true)    
}

er, someone pointed out this doesn't really make sense since that would imply multiple options with the same value. I meant to write something like this:

existingLoginValues = ['foo','bar']
$option=$('<option value="'+ loginOptions[i] +'">'+ loginOptions[i]+'</option>').appendTo(Login);
if (existingLoginValues.indexOf(loginOptions[i]) != -1) {
    $option.attr('selected',true)    
}

the indexOf function is supported in most browsers except (of course) IE6. See "Best way to find an item in a JavaScript Array?"

Solution 3:

Use

$('#Login').selectedIndex = i

Post a Comment for "Add The "selected" Attribute To A Drop Down Option With Jquery"