javascript 从选择标签中获取选定的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10660241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:36:46  来源:igfitidea点击:

Get selected value from select tag

javascript

提问by Caio Bianchi

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.

当我从选项中选择一个值并单击一个按钮时,我想用 javascript 获取选定的值。我究竟做错了什么?我的值总是 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

// javascript代码

var e = document.getElementById("aand_select");
var quantity= e.options[e.selectedIndex].value;

回答by Caio Bianchi

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);??????????

回答by Dan Armstrong

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.

确保您在适当的时间调用 javascript。例如,如果您仅在页面加载时调用它,该值将永远不会改变。确保您是从 onClick() 或其他事件调用它。