Link to home
Start Free TrialLog in
Avatar of ccleebelt
ccleebeltFlag for United States of America

asked on

Validating number of items selected in a muli select box.

I have a multi select box with about 100 optoins.  I need to make sure the user selects at least one, but no more than three options.  I need a javascript function to validate  this behaviour on:

<select multiple name="category_id" size="10">
...<options>
</select>

Thanks.
Avatar of Jeeva Subburaj
Jeeva Subburaj
Flag of United States of America image

<--javascript-->
function check() {
len = document.form1["category_id"].length
i = 0
iCount = 0

for (i = 0; i < len; i++) {
if (document.form1["category_id"][i].selected) {
iCount = iCount  +1
}

if(iCount < 3)
{ alert('ERROR MESSAGE');
document.form1["category_id"].focus();
return false;
}
return true;
}
Avatar of william007
william007

For your reference:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
var minNum=1; var maxNum=3;
function checkListBoxSize(){
oSelect=document.getElementById("category_id");
var count=0;
for(var i=0;i<oSelect.options.length;i++){
      if(oSelect.options[i].selected)
            count++;
      if(count>maxNum){
            alert("Can't select more than 3");
            return false;
      }
}
if(count<1){
alert("Must select at least one item");
return false;
}
return true;
}

</script>
</head>

<body>
<form onsubmit="return checkListBoxSize()">
<select multiple="multiple" id="category_id" name="category_id" size="10" onchange="return false;">
  <option value="a">a</option>
  <option value="b">b</option>
  <option value="c">c</option>
  <option value="d">d</option>
  <option value="e">e</option>
</select>
<input name="" type="submit"/>
</form>
</body>
</html>
ASKER CERTIFIED SOLUTION
Avatar of Steve Bink
Steve Bink
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial