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", "Second", "Third"];
var Login = $( '#Login' );
for ( var i = 0; i < loginOptions.length; i++ ) {
Login.append('<开发者_StackOverflowoption value="'+ loginOptions[i] +'">'+ loginOptions[i] +'</option>');
}
I want to mark one option as "selected" based on whether or not its value matches another variable. so if loginOption[i]
is equal to var existingLoginValue
then set that option to 'selected'
Something that would do
if(loginOptions[i] === existingLoginValue){ print 'selected'; };
Thanks!
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();
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?"
Use
$('#Login').selectedIndex = i
精彩评论