Javascript Maximum Select Test

This demonstrates a javascript solution to limiting the number of checkbox items you can select in a form. For the purposes of this test, you can only select a maximum of three items. After that, you will have to deselect at least one item before you can select another.

Of course, this relies on javascript being available and enabled on the user agent. You should still verify that no more than the desired amount of checkboxes were selected when you process the form...

The Test Form






The Code What Does It...

The Javascript in the <head>

<script type="text/javascript">

var selectcount = 0;
var maxselect = 3;

function countselected(item, selectedstate)
{
    if(selectedstate) {
        if(selectcount >= maxselect) {
            document.getElementById(item).checked = false;
            alert("You can only select "+maxselect+" items");
        }
        else {
            selectcount ++;
        }
    }
    else {
        selectcount --;
    }
}

</script>

The Form in the <body>

<form name="maxselect">

<label for="check1">Check1</label>
<input type="checkbox" name="check1" id="check1" onclick="countselected(this.id, this.checked);"><br>
<label for="check2">Check2</label>
<input type="checkbox" name="check2" id="check2" onclick="countselected(this.id, this.checked);"><br>
<label for="check3">Check3</label>
<input type="checkbox" name="check3" id="check3" onclick="countselected(this.id, this.checked);"><br>
<label for="check4">Check4</label>
<input type="checkbox" name="check4" id="check4" onclick="countselected(this.id, this.checked);"><br>
<label for="check5">Check5</label>
<input type="checkbox" name="check5" id="check5" onclick="countselected(this.id, this.checked);"><br>
</form>

Feel free to use this code if you find it useful. All I ask is a credit and a link back to this page, or to my homepage, which isn't really a lot to ask...


www.nigenet.org.uk | [email protected]