I have a following, easy example:
JavaScript
x
23
23
1
<!DOCTYPE html>
2
<html>
3
<body>
4
5
<select id="mySelect">
6
<option>Apple</option>
7
<option>Orange</option>
8
<option>Pineapple</option>
9
<option>Banana</option>
10
</select>
11
12
13
<script>
14
document.addEventListener("change", function () {
15
var x = document.getElementById("mySelect");
16
var y = x.options[x.selectedIndex];
17
alert(y);
18
}
19
</script>
20
21
</body>
22
</html>
23
when I choose option on my list then no alert pops-up. I also tried with:
JavaScript
1
2
1
var y = x.options[x.selectedIndex].index;
2
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).
JavaScript
1
5
1
document.addEventListener("change", function () {
2
var x = document.getElementById("mySelect");
3
var y = x.options[x.selectedIndex].index;
4
alert(y);
5
}); // missing ) here
JavaScript
1
6
1
<select id="mySelect">
2
<option>Apple</option>
3
<option>Orange</option>
4
<option>Pineapple</option>
5
<option>Banana</option>
6
</select>