count the number of selections in a multiple-selec

2020-02-10 04:56发布

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.

How to do it using java script?

I tried the following but it didn't work for me:

var x = document.getElementById("preference").count;

Thanks in Advance.

5条回答
一夜七次
2楼-- · 2020-02-10 05:31

If < IE8 isn't a concern, you can do a one-liner like document.querySelectorAll("option:checked") to get all the selected options.

查看更多
看我几分像从前
3楼-- · 2020-02-10 05:41

Assume foo is the id of the select.

If you use normal 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:

var count = $('#foo option:selected').length;
查看更多
Juvenile、少年°
4楼-- · 2020-02-10 05:44

Use the :selected selector, like this:

$('#example option:selected').length;
查看更多
家丑人穷心不美
5楼-- · 2020-02-10 05:46
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>
查看更多
再贱就再见
6楼-- · 2020-02-10 05:49

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/

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);
         }  
查看更多
登录 后发表回答