In this thread, it is described how you can fetch the selected value from a drop down box using JavaScript. I’ve been trying to follow the instructions in that thread, but haven’t been able to get it working.
Here’s a minimal (non-working) example of what I’m trying to do. The code should print the value of the second option from the drop down box, but instead I get the following error in the Chrome’s JavaScript console Uncaught TypeError: Cannot read property 'options' of null on row 11 (that is, when I define my second variable).
<html>
<body>
<select name='a_drop_down_box'>
<option value='1'>One</option>
<option value='2' selected='selected'>Two</option>
<option value='3'>Three</option>
</select>
<p id='message'></p>
<script type="text/javascript">
var test = document.getElementById("a_drop_down_box");
var testValue = test.options[test.selectedIndex].value;
document.getElementById('message').innerHTML=testValue;
</script>
</body>
</html>
Did you notice that you haven’t defined an id for the select item?
The
nameattribute is used to identify the form element for requests send using the form. You should use an id to retrieve it from the dom.Alternatively if your select resides inside a form, you could use this: