eveo
eveo

Reputation: 2833

Preserving checkbox state after form resubmission in PHP

CODE:

<input type="checkbox" name="discountedItem" <?php if (isset($_POST['discountedItem'])) echo "checked" . " " . "value='y'"; ?> />

How can I transform this into an if statement so that if it's not checked the value is n?

I tried:

<input type="checkbox" name="discountedItem" <?php if (isset($_POST['discountedItem'])) { echo "checked" . " " . "value='y'"; } else { echo "value='n'"; } ?> />

Didn't work. The value was just NULL.

Upvotes: 0

Views: 198

Answers (2)

Nikolaos Dimopoulos
Nikolaos Dimopoulos

Reputation: 11485

If you check the value, it will be sent to the POST. If you uncheck it it won't.

A way to deal with this is to include a hidden element with the same name as your checkbox that has a placeholder value (something like -10) and your processing script (the one that receives the POST) can check for that value and perform the necessary action

<input type='hidden' name='discountedItem' value='-10' />
<input type='checkbox' name='discountedItem' ....>

There might be however some browser incompatibility with this approach. I have seen in the past that IE will post both values in the POST and one will not overwrite the other (which is what we want really).

The solution to that would be to use just a snippet of javascript and attach it to the onclick event of the checkbox. If the checkbox is unchecked, a new hidden element with the same name and the placeholder value is added to the DOM, and if the checkbox is checked the hidden element is removed.

So your logic will become:

<input type="checkbox" name="discountedItem" <?php if (isset($_POST['discountedItem']) && $_POST['discountedItem'] == '-10') { echo "checked='checked'" . " " . "value='y'"; } ?> />

HTH

Upvotes: 0

mario
mario

Reputation: 145482

The value= is never submitted if the checkbox isn't set.

You can't have your n with a checkbox. Consider a radio button. Or simply adapt your processing logic (the if you referred to) not to look for strings, but any present value.

Upvotes: 1

Related Questions