Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count the number of selections in a multiple-select box

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.

like image 730
coolmego Avatar asked Sep 23 '12 04:09

coolmego


3 Answers

Use the :selected selector, like this:

$('#example option:selected').length;
like image 75
Nelson Avatar answered Nov 09 '22 23:11

Nelson


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;
like image 22
xdazz Avatar answered Nov 09 '22 23:11

xdazz


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);
         }  
like image 20
kannanrbk Avatar answered Nov 09 '22 23:11

kannanrbk