0

I want to make a HTML file with a select box.

So first of all, things are working perfectly fine:

<!DOCTYPE html>
<html>
<body>
  <select id="options">
    <option value="1">Option 1
    <option value="2">Option 2
  </select>
</body>
</html>

So, this code made a select box with 2 options:

Option 1

Option 2

Now I want to use JavaScript to check which option is selected. And I don't know how to do it.

<!DOCTYPE html>
<html>
<body>
  <select id="options">
    <option value="1">Option 1
    <option value="2">Option 2
  </select>
  <script>
    //What here?
  </script>
</body>
</html>

So this is the structure of the code:

There are 2 options:

If the user select option 1, JavaScript will do Command 1.

If the user select option 2, JavaScript will do Command 2.

halfer
  • 19,471
  • 17
  • 87
  • 173
  • 1
    Does this answer your question? https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript – Tarmo May 20 '20 at 07:06

2 Answers2

1

First of all , you have to have the closing option tag </option> . Then you attach an event to the select box (onClick, onChange) and call a function.

<select id="choose-lang" onChange ="ourFunction()">

In function,

function ourFunction(){
    var e = document.getElementById("choose-lang");
    var selectedOptionText = e.options[e.selectedIndex].text;
    console.log(selectedOptionText)
}

If you are looking to print value,

function ourFunction(){
    var e = document.getElementById("choose-lang");
    var selectedOptionValue = e.options[e.selectedIndex].value;
    console.log(selectedOptionValue)
}
Mukesh Keshu
  • 467
  • 2
  • 10
1

You can use this code any dom event like onChange and also you want select option text you can just replace that line var strUser = e.options[e.selectedIndex].text;

function getLangValue(){
var e = document.getElementById("choose-lang")
var strUser = e.options[e.selectedIndex].value;
console.log(strUser)
}
<select id="choose-lang" onChange=getLangValue()>
  <option value="1">Option 2</option>
  <option value="2">Option 1</option>
  </select>
halfer
  • 19,471
  • 17
  • 87
  • 173
Sanat Gupta
  • 814
  • 9
  • 15
  • Thank you so much. This was the first time I see a code snippet working. LOL. But I only see it `console.log` once. And if I change it it wouldn't log it. How would you change it so it logs the `value` onto the console whenever it changes? – Dangerousgame May 20 '20 at 05:38
  • code snippet working on a ready event that's why you get the first option always. you need to use a dom event like `Onchange Onclick` in your code. – Sanat Gupta May 20 '20 at 05:42
  • I just update snippet with `onChange` Dom event now it's working fine you get update value on change the dropdown – Sanat Gupta May 20 '20 at 05:45
  • thank you somebody already posted it but thanks anyway =) – Dangerousgame May 20 '20 at 05:46