Snippet Name: Count checkboxes
Description: Make sure users can only select X number of checkboxes.
Comment: (none)
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> |