How to set the value of a select box element using JavaScript?
In JavaScript, selectedIndex property is used to set the value of a select box element. The selectedIndex property sets or returns the index of the selected value in a drop-down list. Syntax:
Set index: selectObject.selectedIndex = number Return index: selectObject.selectedIndex
Note: Integer number is used for Index at the value place. Example-1: Select a index number.
html
<!DOCTYPE html> < html > < body > < h1 style="color: green;"> GeeksforGeeks </ h1 > < select id="mySelect"> < option >football</ option > < option >Basketball</ option > < option >Hockey</ option > < option >Swimming</ option > </ select > < p > Click the button to select the option element with index "2". </ p > < button onclick="myFunction()"> click me </ button > < script > function myFunction() { document.getElementById( "mySelect").selectedIndex = "2"; } </ script > </ body > </ html > |
Output: Before clicking on button, it stays on index 0: After clicking on button, it go on index 2:
Example-2: If you select selectedIndex = “-1”; it will deselect all the elements of selectbox.
html
<!DOCTYPE html> < html > < body > < h1 style="color: green;"> GeeksforGeeks </ h1 > < select id="mySelect"> < option >football</ option > < option >Basketball</ option > < option >Hockey</ option > < option >Swimming</ option > </ select > < p > Click the button to deselect options. </ p > < button onclick="myFunction()"> Click me </ button > < script > //Here we delselect all the options function myFunction() { document.getElementById( "mySelect").selectedIndex = "-1"; } </ script > </ body > </ html > |
Output: Before clicking on button, it stays on index 0: After clicking on button, all elements gets deselected:
Example-3: If any element is not selected then this property returns -1.
html
<!DOCTYPE html> < html > < body > < h1 style="color: green;"> GeeksforGeeks </ h1 > < select id="mySelect"> < option >football</ option > < option >Basketball</ option > < option >Hockey</ option > < option >Swimming</ option > </ select > < p > Click the button to deselect options. </ p > < button onclick="myFunction()"> Click me</ button > < script > //Here we delselect all the options function myFunction() { document.getElementById( "mySelect").selectedIndex = "-1"; } //here we are taking value of index function yourFunction() { var x = document.getElementById( "mySelect").selectedIndex; document.getElementById( "demo").innerHTML = x; } </ script > < button type="button" onclick="yourFunction()"> Display index </ button > < p id="demo"></ p > </ body > </ html > |
Output : After clicking on button, all elements gets deselected
Here you can see that index return by selectedIndex property is -1
Please Login to comment...