Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the selectedIndex of a select element using getElementById

Tags:

javascript

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;                       

}
like image 860
Darren Avatar asked Jan 28 '26 07:01

Darren


1 Answers

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.

like image 76
nnnnnn Avatar answered Jan 30 '26 20:01

nnnnnn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!