You are here: Re: How do get the state of checkboxes in php? « PHP Programming Language « IT news, forums, messages
Re: How do get the state of checkboxes in php?

Posted by Jerry Stuckle on 09/08/07 01:23

Kelsey Sigurdur wrote:
> On Fri, 07 Sep 2007 13:06:34 -0500, Lorenzo Thurman wrote:
>
>> I have a group of checkboxes drawn by javascript and I need to get each
>> of their states into PHP after submitting the page. I should think I
>> could get them in a POST, but that fails. Anyone have any ideas?
>> TIA
>
> Use an additional hidden input, with the same name as the checkbox and a
> value of 0. In almost all cases you'll want the hidden input to appear in
> the source before the actual checkbox.
>
> When the form is submitted, if the checkbox has been checked, it's value
> will override the hidden input of the same name. If it hasn't been checked
> the hidden input (with its value of 0) will be in the $_POST array.
>
> AFAIK this is the only way to do it as unchecked checkboxes are not passed
> to POST at all.
>

Not at all the only way. Your method depends on the order the browser
sends post data. Sure, they usually send the input fields in the order
the fields appear in the form, but this is not at all required. A
change to the browser will break your pages.

A better way is to have a hidden field with the name of the checkbox, i.e.

<input type=hidden name="cbname[]" value="chkbox1">
<input type=checkbox name="chkbox1">
.....
<input type=hidden name="cbname[]" value="chkbox2">
<input type=checkbox name="chkbox2">

And so on

The names of the checkboxes will now be in the array $_POST['cbname']
and you can check it with something like:

foreach ($_POST['cbname'] as $cbname) {
if (isset($_POST[$cbname]))
echo "Checkbox $cbname is checked<br>\n";
else
echo "Checkbox $cbname is NOT checked<br>\n";
}

This is independent of the order in which the browser sends the form data.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация