frequently ask ? : Computers : Programming : Languages : JavaScript : Forms : SELECT

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

31 of 34 people (91%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I restrict the number of selections in a select multiple element?

Feb 6th, 2002 15:07
Martin Honnen,


The following defines a function 
  checkMaxSelected
taking a select element object as the first argument and the maximum 
number of options to be selected as the second argument. The function 
is to be called in the onchange handler and then fires an alert if the 
maximum number of selections is exceeded and discards that selection.
<html>
<head>
<title>
max selected check for select element
</title>
<script type="text/javascript">
function checkMaxSelected (select, maxSelected) {
  if (!select.storeSelections) {
    select.storeSelections = new Array(select.options.length);
    select.selectedOptions = 0;
  }
  for (var i = 0; i < select.options.length; i++) {
    if (select.options[i].selected && 
        !select.storeSelections[i]) {
      if (select.selectedOptions < maxSelected) {
        select.storeSelections[i] = true;
        select.selectedOptions++;
      }
      else {
        alert('Selection will be discarded as limit of ' + maxSelected 
+ ' is reached.');
        select.options[i].selected = false;
      }
    }
    else if (!select.options[i].selected &&
             select.storeSelections[i]) {
      select.storeSelections[i] = false;
      select.selectedOptions--;
    }
  }
} 
</script>
</head>
<body>
<form name="formName">
<select name="selectName" multiple="multiple"
        onchange="checkMaxSelected(this, 2);"
>
<option>option 0</option>
<option>option 1</option>
<option>option 2</option>
<option>option 3</option>
</select>
</form>
</body>
</html>