PHP Checkbox Problem

This topic is 3889 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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

Share on other sites
<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.

Share on other sites
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.

Share on other sites
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

Share on other sites
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.

Share on other sites
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!