Javascript 如何使用javascript从列表框中获取多个选定的值和项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12775912/
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
how to get multiple selected values and items from listbox using javascript
提问by R J.
<!DOCTYPE html>
<html>
<script>
function getValue()
{
??var x=document.getElementById("sel");
for (var i = 0; i < x.options.length; i++) {
if(x.options[i].selected ==true){
alert(x.options[i].selected);
}
}
}
</script>
</head>
<body>
<select multiple="multiple" id="sel">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="button" value="Get Value" onclick="getValue()"/>
</body>
</html>
This is my code. how do i get all the selected values from listbox using javascript.The above code showing show true for all selected value.
这是我的代码。我如何使用 javascript 从列表框中获取所有选定的值。上面的代码显示所有选定的值都为真。
回答by Peter Wilkinson
Replace
代替
if(x.options[i].selected ==true){
alert(x.options[i].selected);
}
with
和
if(x.options[i].selected){
alert(x.options[i].value);
}
回答by Konstantin Dinev
I suggest that you do it using jQuery like this:
我建议你像这样使用 jQuery:
var selected = $('#sel option:selected');
If you prefer not to use jQuery then disregard this answer and refer to the other ones.
如果您不想使用 jQuery,请忽略此答案并参考其他答案。
回答by Rm558
use selectedOptions
使用selectedOptions
for (var i = 0; i < x.selectedOptions.length; i++) {
alert(x.selectedOptions[i].value);
}
回答by Pankaj Chauhan
Solution with same example
同一个例子的解决方案
<!DOCTYPE html>
<html>
<script>
function getValue()
{
var x=document.getElementById("sel");
for (var i = 0; i < x.options.length; i++) {
if(x.options[i].selected ==true){
alert(x.options[i].value);
}
}
}
</script>
</head>
<body>
<select multiple="multiple" id="sel">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="button" value="Get Value" onclick="getValue()"/>
</body>
</html>