javascript

I want to get option selected with js?


I want get option selected with js but my code returns "undefined". Where is the error?

const aaa = document.querySelector("#test")

const rng = aaa.addEventListener("change",(e)=>{
  return e.target.selectedOptions[e.target.selectedIndex].text
})
console.log(rng)
<select id="test">
      <option value="a">a</option>
      <option value="b">b</option>
      <option value="c">c</option>
</select>


Solution

  • First, you are assigning the addEventListener to your const rng, and it's returning undefined that's why you get undefined, the callback function will not return to this context

    Second, selectedOptions here, for a single select input, will be only one item represented as an object where you can get the element itself by the key 0, you shouldn't try to access it by the real index in the options list

    Finally, get the innerText of this element

    ex:

    const selectElement = document.querySelector("#test")
    
    selectElement.addEventListener("change",(e)=>{
      console.log(e.target.selectedOptions[0].innerText)
    })
    <select id="test">
          <option value="a">a</option>
          <option value="b">b</option>
          <option value="c">c</option>
    </select>

    Or you can get the element using querySelector:

    const selectElement = document.querySelector("#test")
    
    selectElement.addEventListener("change",(e)=>{
      console.log(selectElement.querySelector("option:checked").innerText)
    })
    <select id="test">
          <option value="a">a</option>
          <option value="b">b</option>
          <option value="c">c</option>
    </select>