CoderZone.org

Category: >> JavaScript >> Count checkboxes Bookmark and Share

<< lastnext >>

Snippet Name: Count checkboxes

Description: Make sure users can only select X number of checkboxes.

Comment: (none)

Author: CoderZone
Language: JAVASCRIPT
Highlight Mode: JAVASCRIPT
Last Modified: February 27th, 2009

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script>
function check(){
count = 0;
str = '';
    for(x=0; x<document.form1.elements["checkbox[]"].length; x++){
        if(document.form1.elements["checkbox[]"][x].checked==true){
            str += document.form1.elements["checkbox[]"][x].value + ',';
            count++;
        }
    }
 
    if(count==0){
        alert("You must choose at least 1");
        return false;
    }
    else if(count>3){
        alert("You can choose a maximum of 3");
        return false;
    }
    else {
    alert("You chose " + count + ": " + str.substring(0,str.length-1));
    document.form1.submit();
    }
}
</script>
</head>
 
<body>
 
<form name="form1" id="form1" method="post" action="" onsubmit="return check()">
  <p>
    <input type="checkbox" name="checkbox[]" value="red" />
  Red<br />
  <input type="checkbox" name="checkbox[]" value="green" />
  Green<br />
  <input type="checkbox" name="checkbox[]" value="blue" />
  Blue<br />
  <input type="checkbox" name="checkbox[]" value="black" />
  Black<br />
  <input type="checkbox" name="checkbox[]" value="white" />
  White<br />
  <input type="checkbox" name="checkbox[]" value="yellow" />
  Yellow<br />
  <input type="checkbox" name="checkbox[]" value="purple" />
  Purple
</p>
  <p>
    <input type="submit" name="Submit" value="Click Me" />
</p>
</form>
</body>
</html> 
 
There haven't been any comments added for this snippet yet. You may add one if you like.  Add a comment 
© coderzone.org | users online: 8