Limit number of selected values in listbox

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?
 
A

ATR2000

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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top