Home > OS >  How do I get selected value of dropdown list in javascript?? (without selected attribute)
How do I get selected value of dropdown list in javascript?? (without selected attribute)

Time:09-04

I would like to get the selected option of a dropdown list to display a second question accordingly. So, if my code is

<form>
      <label for="stall">Choose a stall: </label>
      <select name="stall" id="stall">
        <option value="blank"></option>
        <option value="Stall 1: Drinks">Stall 1: Drinks</option>
        <option value="Stall 2: Mama Baked Rice">Stall 2: Mama Baked Rice</option>
        <option value="Stall 3: Mixed Veg Rice">Stall 3: Mixed Veg Rice</option>
        <option value="Stall 4: Noodles">Stall 4: Noodles</option>
        <option value="Stall 5: Korean and Jap">Stall 5: Korean and Jap</option>
        <option value="Stall 6: Western">Stall 6: Western</option>
        <option value="Stall 7: Mama Pasta">Stall 7: Mama Pasta</option>
        <option value="Stall 8: Muslim">Stall 8: Muslim</option>
      </select>
  </form>

and would like to display second question (menu) based on the stall chosen, how do I do that using javascript?

CodePudding user response:

Simply attach the event (change) and inside the event handler function capture the the value like the following way:

var el = document.querySelector('#stall');
el.addEventListener('change', function(){
  console.log(this.value);
});
<form>
      <label for="stall">Choose a stall: </label>
      <select name="stall" id="stall">
        <option value="blank"></option>
        <option value="Stall 1: Drinks">Stall 1: Drinks</option>
        <option value="Stall 2: Mama Baked Rice">Stall 2: Mama Baked Rice</option>
        <option value="Stall 3: Mixed Veg Rice">Stall 3: Mixed Veg Rice</option>
        <option value="Stall 4: Noodles">Stall 4: Noodles</option>
        <option value="Stall 5: Korean and Jap">Stall 5: Korean and Jap</option>
        <option value="Stall 6: Western">Stall 6: Western</option>
        <option value="Stall 7: Mama Pasta">Stall 7: Mama Pasta</option>
        <option value="Stall 8: Muslim">Stall 8: Muslim</option>
      </select>
  </form>

  • Related