Limit number of selected values in listbox

  • Thread starter Thread starter Doogie
  • Start date Start date
D

Doogie

I'm using a ASP ListBox and I have it set to allow multiple selects.
I'd like to prevent the user from selecting more than a set number of
values in the list box at a time (i.e. 4). What would be the best way
to accomplish this?
 
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_23384906.html

Change your <select> to

<select name="Category1" id="Category1" onChange="validateListBox(4);"
multiple size="5">

then add the following script to head section

<script>
var origSelect = new Array();
function validateListBox(max){
var newSelect = new Array();
var oSelect=document.getElementById("Category1");
var count=0;
for(i=0;i<oSelect.length;i++){
if(oSelect.options.selected){
newSelect.push(i);
++count;
}
}
for(i=0;i<newSelect.length;i++){
//alert("Hallo="+newSelect);

}
if(count>max){
alert("You can only choose "+max+" or fewer categories");
var lastItem=0;
var match=false;
for(i=0;i<newSelect.length;i++){
match=false;
for(j=0;j<origSelect.length;j++){
if(newSelect==origSelect[j]){
match=true;
break;
}
}
if(!match){
oSelect.options[newSelect].selected=false;
break;
}
}
}else{
origSelect=newSelect;
}
}
</script>
 
Back
Top