Log in

View Full Version : Web Form Processing a Checkbox



jamez100
09-22-2009, 10:50 AM
Hi there

Further to my post yesterday about processing webform, thanks I now have it working (mostly).

But I'm having problems processing a check box.

I just need to set the variable to 'checked' or 'unchecked' for the checkbox.

Here my code so far.

$ch1 = 'unchecked';

if ($ch1 = 'yes') {
$ch1 = 'checked';
}

if ($ch1 == 'checked') {
$ch1 = 'The checkbox is checked';
}
else
{
$ch1 = 'The checkbox is unchecked';
}

At the moment the vaule return is 'checked' whether the checkbox is actually ticked or not (always returns true).

Thanks, James

forum_amnesiac
09-22-2009, 11:43 AM
There is an error with your logic, you are setting the value of $ch1 to always be "unchecked" then testing if it is "yes".


$ch1 = 'unchecked';

if ($ch1 = 'yes') {
$ch1 = 'checked';
}

Take out the first line and change the second part like this:


if ($ch1 == 'yes') {
$ch1 = 'checked';
}

The other thing you should do if that doesn't work is to echo the value of $ch1 and then test it to see what it contains when the checkbox is checked and when it is not.

jamez100
09-22-2009, 11:59 AM
HI

Thanks for your advice, I have since modified the code but still having problems getting it to work.

$ch1 = $_POST['thechkbox'];

if ($ch1 == 'checked') {
$ch1 = 'checked';
}
else
{
$ch1 = 'no not checked';
}

If I leave the checkbox unticked I get the following error:
Undefined index: thechkbox
IF I tick the checkbox I get no error.

Any pointer would be greatly appreciated.

Thanks again, James

forum_amnesiac
09-23-2009, 06:21 AM
Can you post the HTML for the checkbox?

You probably need to set a default value for the checkbox or have a validation process that ensures that the field has been set.

prasanthmj
09-23-2009, 03:21 PM
use the isset() function.



if(isset($_POST['thechkbox']) &&
$_POST['thechkbox'] == 'checked')
{

}


The tutorial in the page below might help:
checkbox in a PHP form (http://www.html-form-guide.com/php-form/php-form-checkbox.html)