Reputation: 1970
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>
Upvotes: 0
Views: 10404
Reputation: 2392
You forgot to add id to your select tag
var e = document.getElementById("a_drop_down_box");
var strUser = e.options[e.selectedIndex].value;
Will return 2. If you want Two
, then do this:
var e = document.getElementById("a_drop_down_box");
var strUser = e.options[e.selectedIndex].text;
Here is a simple example http://jsfiddle.net/VCerV/3/
Upvotes: 1
Reputation: 5782
document.getElementById("a_drop_down_box");
Did you notice that you haven't defined an id for the select item?
The name
attribute 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:
document.getElementById("myForm").elements["a_drop_down_box"];
Upvotes: 3
Reputation: 34556
The dropdown's name
attribute is "a_drop_down_box" - you're calling it as thought this was its id
.
Any time you get an '...of undefined' error it means the object (or element, in your case) you think you're working on has not been found. So always confirm this before wondering why errors are happening. In your case, you could have done:
alert(test); //undefined - no element found with that ID
Upvotes: 1
Reputation: 20598
You forgot to give your <select>
an id
attribute.
<html>
<body>
<select id='a_drop_down_box' 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>
Upvotes: 1