admin管理员组文章数量:1297056
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('<option 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!
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('<option 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!
Share edited Mar 11, 2010 at 20:03 rg88 asked Mar 11, 2010 at 19:58 rg88rg88 21k18 gold badges79 silver badges110 bronze badges3 Answers
Reset to default 7I'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
本文标签: javascriptAdd the quotselectedquot attribute to a drop down option with jQueryStack Overflow
版权声明:本文标题:javascript - Add the "selected" attribute to a drop down option with jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741628471a2389219.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论