Javascript 计算多选框中的选择数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12549770/
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
count the number of selections in a multiple-select box
提问by coolmego
I have a multiple selection list which have more than 5 options, and i want to count the number of selection of the options selected by the user.
我有一个多选列表,其中有 5 个以上的选项,我想计算用户选择的选项的选择次数。
How to do it using java script?
如何使用java脚本来做到这一点?
I tried the following but it didn't work for me:
我尝试了以下操作,但对我不起作用:
var x = document.getElementById("preference").count;
Thanks in Advance.
提前致谢。
回答by xdazz
Assume foo
is the id of the select.
假设foo
是选择的id。
If you use normal javasript:
如果你使用普通的javasript:
var options = document.getElementById('foo').options, count = 0;
for (var i=0; i < options.length; i++) {
if (options[i].selected) count++;
}
If you use jQuery:
如果您使用 jQuery:
var count = $('#foo option:selected').length;
回答by kannanrbk
You can try this to get multiple select boxes user selected options count and their selected names. Try this link http://jsfiddle.net/N6YK8/8/
你可以试试这个来获得多个选择框用户选择的选项计数和他们选择的名称。试试这个链接http://jsfiddle.net/N6YK8/8/
function getCount(){
var comboBoxes = document.querySelectorAll("select");
var selected = [];
for(var i=0,len=comboBoxes.length;i<len;i++){
var combo = comboBoxes[i];
var options = combo.children;
for(var j=0,length=options.length;j<length;j++){
var option = options[j];
if(option.selected){
selected.push(option.text);
}
}
}
alert("Selected Options '" + selected + "' Total Count "+ selected.length);
}
回答by Nelson
Use the :selected
selector, like this:
使用:selected
选择器,如下所示:
$('#example option:selected').length;
回答by Jan Sommer
If < IE8 isn't a concern, you can do a one-liner like document.querySelectorAll("option:checked")
to get all the selected options.
如果 < IE8 不是问题,您可以执行单行操作document.querySelectorAll("option:checked")
以获取所有选定的选项。
回答by jaydev thakkar
function SelectPage(elem)
{
alert(elem);
}
<select id="page" name="section" onChange="SelectPage(this);" id="num">
<option value="">Select Section</option>
<option value="1">Page-1</option>
<option value="2">Page-2</option>
<option value="3">Page-3</option>
<option value="4">Page-4</option>
<option value="5">Page-5</option>
</select>