PHP Checkbox Problem

Started by
4 comments, last by nolongerhere 16 years, 11 months ago
I have a form that has about 15 checkboxes that POST the result in a single array. Then I am looping through that array and checking if each checkbox is "on" or "off" but it seems that it only sends a result if it is "on", so I end up with say, an array of 5 "on"s instead of 5 "on"s and 10 "off"s. Ive read multiple tutorials that say it does send "off" for unchecked boxes but it seems just not to send me a result at all. Someone please help! Thanks
Advertisement
<input type="hidden" name="check1" value="off" /><input type="checkbox" name="check1" /><input type="hidden" name="check2" value="off" /><input type="checkbox" name="check2" /><input type="hidden" name="check3" value="off" /><input type="checkbox" name="check3" />


It's a bit of a kludge but it works.
No, that doesnt work because when the checkbox is checked, I recieve an OFF and an ON. That WOULD work I suppose, if I wasnt using an array for all the checkbox's name, like I mentioned in my first post.
The contents of the array comes from the value attribute assigned to the checkbox, so you should be able to do something like this:

HTML:
<input type="checkbox" name="stuff[]" value="0" />Item 1<br /><input type="checkbox" name="stuff[]" value="1" />Item 2<br /><input type="checkbox" name="stuff[]" value="2" />Item 3<br /><input type="checkbox" name="stuff[]" value="3" />Item 4<br />...<input type="checkbox" name="stuff[]" value="14" />Item 15<br />


PHP:
$things = $_POST['stuff'];$s = str_repeat('0', 15);foreach ($things as $marked_thing)    $s[$marked_thing] = '1';


Edit: Small fix - the values should start from 0 since strings uses zero-base indexing (alternatively, subtract 1 from the $marked_thing before using it as an index).

Edit 2: I'm sure there was some reason I thought you were using the values to build a string of 0s and 1s, but now I can't find where you said it. Anyway, the basic idea can still be used if you want to do something else with the data.

John B
The best thing about the internet is the way people with no experience or qualifications can pretend to be completely superior to other people who have no experience or qualifications.
Ah, I thought you were iterating over them by name or something. It isn't a PHP problem. The html form doesn't send the value for off if the checkbox isn't checked. I've used the previous hack on many occasions but I've never needed to use a form array. Can you redesign and iterate based off of the checkbox name?

for($i = 0; $i < $total_check_boxes; $i++){  print $_REQUEST["checkbox_$i"];}


Otherwise, you should be able to do some pre-processing on the form data with js before submitting it.
Thanks you guys, I took your advice tstrimp and changed the names to $cbX. I dont set them all to OFF though, I just check if it isset(). Works nicely, thanks!

This topic is closed to new replies.

Advertisement