skip to Main Content

I want to get select value after I change it but it’s not working (even responding).

const sortSelect = document.getElementById("sortSelect");

function sortData() {
  console.log(sortSelect.selectedOptions[0].value);
}
<select onchange="sortData();" id="sortSelect" class=" border border-gray-300 bg-gray-50 p-[.5rem] pl-[2rem] cursor-pointer rounded-xl text-[16px] focus:ring-gray-300 focus:border-gray-400 w-[16rem]" name="sortSelect">
  <option>جدیدترین</option>
  <option>قدیمی ترین</option>
  <option>بیشترین زمان</option>
  <option>کمترین زمان</option>
</select>

2

Answers


  1. HTML:

    `<select
        onchange="sortData();"
        id="sortSelect"
        class=" border border-gray-300 bg-gray-50 p-[.5rem] pl-[2rem] cursor-pointer rounded-xl text-[16px] focus:ring-gray-300 focus:border-gray-400 w-[16rem]"
         name="sortSelect"
         >
         <option>جدیدترین</option>
         <option>قدیمی ترین</option>
         <option>بیشترین زمان</option>
         <option>کمترین زمان</option>
    </select>`
    

    JS:

    var e = document.getElementById("sortSelect");
    var value = e.options[e.selectedIndex].text;
    console.log(value);
    

    This should return the (text) value of the selected option

    Login or Signup to reply.
  2. Try with this code:

    const sortSelect = document.getElementById("sortSelect");
    
    function sortData() {
      console.log(sortSelect.value);
    }
    <select onchange="sortData();" id="sortSelect" name="sortSelect">
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
    </select>

    I change the value to 1,2,3,4 but the concept is the same.

    It also semed like yuor snippet worked.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search