Page 1 of 1
testing for checkboxes
Posted: Mon Dec 19, 2005 8:11 am
by Skittlewidth
What would be the most efficient way of checking 27 checkboxes to see if they are set (given that they pass no value at all if left blank).
I don't want to type if (isset()){....} 27 times. Currently they have meaningful names. Should I rename them all to have a prefix and unique numbers and loop through them, and get confused about their function later when I revisit the code, or is there another way?
My brain has already left for its christmas vacation by the looks of things...

Posted: Mon Dec 19, 2005 8:28 am
by onion2k
Code: Select all
<form method="post">
<input type="checkbox" name="checkboxgroup[]" value="1">
<input type="checkbox" name="checkboxgroup[]" value="2">
<input type="checkbox" name="checkboxgroup[]" value="3">
<input type="checkbox" name="checkboxgroup[]" value="4">
<input type="checkbox" name="checkboxgroup[]" value="5">
<input type="submit">
</form>
Code: Select all
if (is_array($_POST['checkboxgroup'])) {
echo "The following boxes were set: ".implode(",",$_POST['checkboxgroup']);
}
That's the easy way .. however .. I don't agree with this line: "
I don't want to type if (isset()){....} 27 times" .. it's just lazy. You're trying to avoid a bit of typing, and you're sacrifising the integrity, maintainability, readability, and security of your code in the process. Checkboxes should be grouped logically. If there are 27 seperate things to tick then you
should have 27 seperate isset() functions.
Posted: Mon Dec 19, 2005 8:34 am
by Skittlewidth
I told you my brain had left me.
Quite frankly, I'm embarrassed! I always usually use arrays for groups of checkboxes... what an idiot!
More sherry anyone? *Hic*
Edit: Onion2k, I agree with you about the way checkboxes are grouped though. There is a school of thought that says you shouldn't ever use the value attribute with a checkbox, and that the name is the checked value. (Hence me giving meaningful names). In this case 20 of the checkboxes do relate to a specific subject, so I could get away with the array method. But I wouldn't use this method to check an entire page of checkboxes if they weren't related.
Sorry if it sounded lazy about the if (isset()) thing. I was actually concerned about how the code would look on the page for editting later. I was trying to keep things neat.