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">

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

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');
return false;
return true;
Avatar of william007

For your reference:

<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
var minNum=1; var maxNum=3;
function checkListBoxSize(){
var count=0;
for(var i=0;i<oSelect.options.length;i++){
            alert("Can't select more than 3");
            return false;
alert("Must select at least one item");
return false;
return true;


<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>
<input name="" type="submit"/>
Avatar of Steve Bink
Steve Bink
Flag of United States of America image

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