简体   繁体   中英

How to change the selectedIndex of a select element using getElementById

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;                       

}

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;
    }
}

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.

或selected.value = [选项值]

尝试:

selected.selectedIndex = [Your index]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM