How to use selectedIndex Property In Javascript
The selectedIndex
property is a property of the <select>
element in HTML, and it is used in JavaScript to get or set the index of the currently selected option in the dropdown list. The index is a zero-based integer indicating the position of the selected option among the <select>
element’s options.
Example: In this modified code, the selectedIndex
property is used to get the index of the selected option, and then options[selectedIndex]
is used to access the selected option. The value
and text
properties of the selected option are then used to display the value and text in an alert.
HTML
<!DOCTYPE html> < html > < head > < title > Get text of option tag by value using pure JavaScript </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > w3wiki </ h1 > < p > Click on the button to get the text of options </ p > < select id = 'GFG_list' > < option value = 'GFG_1' >GFG_A</ option > < option value = 'GFG_2' >GFG_B</ option > < option value = 'GFG_3' >GFG_C</ option > </ select > < br >< br > < button id = "GFG_Button" onclick = "getText()" > getText </ button > < script > function getText() { const selectedIndex = document.getElementById('GFG_list').selectedIndex; const selectedOption = document.getElementById('GFG_list').options[selectedIndex]; alert("Value - " + selectedOption.value + ", Text - " + selectedOption.text); } </ script > </ body > </ html > |
Output:
How to get the text of option tag by value using JavaScript ?
To get the text of the option tag by value using JavaScript, we have multiple approaches. we are going to learn how to get the text of the option tag by value using JavaScript.
These are the following approaches that are discussed below:
Table of Content
- Using value Property
- Using Object.values() Method
- Using selectedIndex Property