Friday, October 29, 2010

Limit number of selections in a Multiple Select Box

Call this function on select box 's onchange event..

<script type="text/javascript">

<!--//   LIMIT MULTIPLE SELECTED OPTIONS SCRIPT || 01-21-2005   \\;
var selectedOptions = []; // Written by: WillyDuitt@hotmail.com \\;
 function countSelected(select,maxNumber){
   for(var i=0; i<select.options.length; i++){
     if(select.options[i].selected && !new RegExp(i,'g').test(selectedOptions.toString())){
        selectedOptions.push(i);
     }

     if(!select.options[i].selected && new RegExp(i,'g').test(selectedOptions.toString())){
      selectedOptions = selectedOptions.sort(function(a,b){return a-b}); 
       for(var j=0;j<selectedOptions.length; j++){
         if(selectedOptions[j] == i){
            selectedOptions.splice(j,1);
         }
       }
     }

     if(selectedOptions.length > maxNumber)
     {
        alert('You may only choose '+maxNumber+' options!!');
           for(var i=0; i<select.options.length; i++){

        select.options[i].selected = false;
        selectedOptions.pop();
        }
      
        document.body.focus();        return true;
     } 
   }   
 }
</script>

No comments:

Post a Comment