I have a following, easy example:
<!DOCTYPE html> <html> <body> <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <script> document.addEventListener("change", function () { var x = document.getElementById("mySelect"); var y = x.options[x.selectedIndex]; alert(y); } </script> </body> </html>
when I choose option on my list then no alert pops-up. I also tried with:
var y = x.options[x.selectedIndex].index;
but can’t return index number of given option. When I use .text instead of .index (to get text from option) it also doesn’ work
Advertisement
Answer
There is a syntax issue (missing the addEventListener
closing parenthesis).
document.addEventListener("change", function () { var x = document.getElementById("mySelect"); var y = x.options[x.selectedIndex].index; alert(y); }); // missing ) here
<select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select>