Twitter Facebook Google+ LinkedIn Pinterest Tumblr Reddit
Question

Why selectedIndex doesn't work in my code?

Tags: html javascript
Date:
Status:Resolved
Question Id:9

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

Answer
Date:
Correct:No

You should open the console and check for errors. Your code has unbalanced parentheses. Should be closed as typo. 

Answer
Date:
Correct:No

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>
Answer
Date:
Correct:Yes

you want to access the textContent from the selected option ?
(because its value is directly accessible on the select)

the event listener must also be used on the select, to use a this

const mySelect = document.getElementById('my-select')

mySelect.addEventListener("change", function ()
  {
  console.clear()
  console.log( 'value=', this.value, ' || content=', this.options[this.selectedIndex].textContent)
  })

<select id="my-select">
  <option value="A">Apple</option>
  <option value="O">Orange</option>
  <option value="P">Pineapple</option>
  <option value="B">Banana</option>
</select>

Your Answer

Review Your Answer