When I select a value from the option and click on a button, I want to fetch the selected value with javascript. What am I doing wrong? My value is always 1.
<select id="aand_select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
// javascript code
var e = document.getElementById("aand_select");
var quantity= e.options[e.selectedIndex].value;
When I select a value from the option and click on a button, I want to fetch the selected value with javascript. What am I doing wrong? My value is always 1.
<select id="aand_select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
// javascript code
var e = document.getElementById("aand_select");
var quantity= e.options[e.selectedIndex].value;
Share
Improve this question
asked May 18, 2012 at 21:59
user1395001user1395001
5
-
Why don't you use
e.value
instead? – MaxArt Commented May 18, 2012 at 22:03 - still value is 1 when I select 5 for example – user1395001 Commented May 18, 2012 at 22:05
- Works on my fiddle: jsfiddle/QPvHL – Heretic Monkey Commented May 18, 2012 at 22:07
-
And
e.value
works too if I edit your fiddle. I must say: obviously. – MaxArt Commented May 19, 2012 at 0:49 -
@AndrejHefner Are you sure that
<select>
is the only element with id "aand_select"? Maybe there's another one before and that's whatdocument.getElementById
gets. – MaxArt Commented May 19, 2012 at 0:52
2 Answers
Reset to default 3This apparently will do
var e = document.getElementById("aand_select");
e.addEventListener('change', function(){
var quantity= e.options[e.selectedIndex].value;
console.log(quantity);
},false);
Make sure that you are calling the javascript at the appropriate time. For example if you are calling it only when the page loads, the value will never change. Make sure you are calling it from an onClick() or some other event.