0

Sample of <select> HTML form element from W3Schools (a bit modified):

<select>
  <option value="a">Option A</option>
  <option value="b">Option B</option>
  /*...*/
</select>

As far as I could see, neither option nor select has id property, so the good old document.getElementById("name of select element").value does not work.

But then, how can I put the value attribute of the option that is selected in the list into a JS variable?

I'm aware that it can be done by a function call, e.g. when I push a button element, but what do I have to write into that function?

Zoltán Schmidt
  • 1,286
  • 2
  • 28
  • 48
  • @DevonBernard oh, thanks! Had no intention to write an actual duplicate, but I had a bit hard time finding relevant answers. Google refused to prefer SO questions somehow when I was searching. – Zoltán Schmidt Mar 22 '16 at 20:32

2 Answers2

2

Aside from just giving it an id, you can add an onchange event:

<select onchange="yourfunction(this.value)">
...

There are also other ways to access elements in your DOM. For example, assuming this is the only (or first) select on your page you could access its value with a line like this:

var val = document.getElementsByTagName("select")[0].value;
jayms
  • 3,828
  • 2
  • 11
  • 18
0

If you don't have an id to work with, the DOM provides a few other APIs that you can use, but probably the most versatile is:

 document.querySelector("CSS Selector Here");

So, you could use a selector that finds the select element by the tag name select or by its position in the DOM or by a class name applied to it, etc.

Then, to get the value, you'd write this:

 var val = document.querySelector("CSS Selector Here").selectedIndex.value;
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71