最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get selected value from select tag - Stack Overflow

programmeradmin6浏览0评论

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 what document.getElementById gets. – MaxArt Commented May 19, 2012 at 0:52
Add a ment  | 

2 Answers 2

Reset to default 3

This 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.

发布评论

评论列表(0)

  1. 暂无评论