View Full Version : number of checkbox selected

02-15-2006, 07:45 AM
i have a code that should trap that only 1 checkbox should be selected but i don't know how????? any suggestions please please plase???
thanks in advance :)

02-15-2006, 07:53 AM
Do you mean that you are looking for a script to check and make sure that only one check box is checked?

If so I'd recommend a client-side language (javascript) to do so as to not tie up my server. But it can be done in PHP as well.

Create an array by naming all the check boxes the same name and then run a for loop to check which ones have a value of being checked.


You could simply use radio buttons :D

02-15-2006, 03:53 PM
If so I'd recommend a client-side language (javascript) to do so as to not tie up my server.
You need to do it in PHP. Javascript is just a nice for the user, but if JS is disabled then it could break your script.

Here is an example

<!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">
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
function check(){
count = 0;
str = '';
for(x=0; x<document.form1.elements["checkbox[]"].length; x++){
str += document.form1.elements["checkbox[]"][x].value + ',';

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));

echo "You chose: <br>";

foreach($_POST['checkbox'] as $key => $val){
echo "$key: $val <br />";
echo "Something went wrong. Try again.";
<form name="form1" id="form1" method="post" action="" onsubmit="return check()">
<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" />
<input type="submit" name="Submit" value="Click Me" />

02-16-2006, 03:37 AM
:) :) :)

02-16-2006, 03:40 AM
y thank you for the idea!thanks a lot for giving me an example.:thumbsup:
It is in a different concept but it did help me to have other idea! Thanks a lot p&#246;!!!!! God Bless!!!! :)

You could simply use radio buttons :D

err..i have a check all, delete, and edit buttons,.i choose checkboxes so the user can select all the checkboxes he wants to delete and choose only one what he wants to edit..but still thank you for the concern :)