Add "selected" attribute to dropdown using jQuery

How do I add a "selected" attribute to a dropdown menu based on this option corresponding to some variable?

This 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 its value matches another variable. so if loginOption[i]

equal var existingLoginValue

then set this option to "selected"

Something that would do

if(loginOptions[i] === existingLoginValue){ print 'selected'; };

      

Thank!

0


source to share


3 answers


I use .val()

at the end of your method, this sets based on the value, for example:

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

      



Likewise, to get a value, call it without any parameters, for example:

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

      

+7


source


If you only want to make one value, then yes, it works val()

. 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 that it doesn't make sense as it implies multiple options with the same meaning. I wanted 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 feature is indexOf

supported in most browsers except (of course) IE6. See Best way to find an element in a JavaScript array?

+1


source


Using

$('#Login').selectedIndex = i

      

0


source







All Articles