Reputation: 793
I want to do something similar to this but I am unable to change the selectedIndex value this way:
var selected = document.getElementById("state-select");
switch (state) {
case 'VA':
selected.options[selected.selectedIndex] = 0;
break;
case 'NC':
selected.options[selected.selectedIndex] = 1;
break;
case 'SC':
selected.options[selected.selectedIndex] = 2;
break;
}
Upvotes: 2
Views: 33139
Reputation: 150030
For this purpose you don't need to be doing anything with options
, you can change the selected element by setting the .selectedIndex
property of your select element directly:
...
case 'VA':
selected.selectedIndex = 0;
break;
// etc.
(Assuming this is a single-select select element.)
I believe if you set selectedIndex
to -1 it will leave no options selected.
Upvotes: 5
Reputation: 11068
switch
statements are cool, but using a hash to do the work can be a lot more flexible. As seen below, you can just check if the state is in the hash, and if so, use it.
var selected = document.getElementById("state-select"),
states = { 'VA' : 0,
'NC' : 1,
'SC' : 2
};
// if `state` ( not sure what it is ) is in the hash
if ( states[ state ] !== undefined ) {
//select option based on the hash
selected.selectedIndex = states[ state ];
}
if you need to select/assign-the-select by value, you can iterate over the values, or use qSA or a library like jQuery or dojo to get it.
<select id="state-select">
<option value="1">NC</option>
<option value="2">SC</option>
</select>
Using jQuery
// select SC
$( '#state-select' ).val( 2 );
Iterating
var sel = document.getElementById( 'state-select' ),
opts = sel.options;
// loop through the options, check the values
for ( var i = 0; i < opts.length; i++ ) {
// assuming 2 would be states[ state ] or whatevs
if ( opts[i] == 2 ) {
// set to this index
sel.selectedIndex = i;
// stop iterating
break;
}
}
Upvotes: 5