2

If I have a form with two checkboxes that have have the same array as name attribute

name="1_1[]"

and neither of those checkboxes is ticked, is there any way I can know they were present in the form? These fields are not being sent through the $_POST array if they are unchecked.

I'm asking this cause these name values are being generated dynamically, I don't always know what they are and I have to validate them (make sure at least one of the two is checked).

Do I have to start using hidden fields to send the name attribute values through, or is there a better way?

1
  • Put this in above the checkboxes: <input type="hidden" name="1_1[]" value="0" /> EDIT: Forgot to read the last line. I actually use the hidden fields myself and I think it is the easiest way. Else you should validate it at the server side page whether the field is set or not. Commented Mar 19, 2011 at 22:34

2 Answers 2

2

Using a hidden field would probably be the most sensible way if you really can't get to the data on the receiving page, if you want to keep on using checkboxes. You can't get a checkbox to send a value if it's unchecked, that's how they work.

On the other hand, the receiving page not knowing about what data to expect sounds really odd. Can't you just re-fetch the same data?

Sign up to request clarification or add additional context in comments.

4 Comments

The receiving page doesn't know what data to expect cause the form is built dynamically (ala surveymonkey) and the name param contains concatenated DB id's. Thanks, I'll go with hidden fields.
@stef: Where do you get the data that defines what fields to display in the first place?
This is part of a survey designer application, so the fields' parameters are stored in a DB.
@stef: Can't you just get the parameters off the DB again and then compare them with the POST data?
1

The fact that they're not in the $_POST array means you can use isset() to see if they've been set.

If you've got two checkboxes and one needs to be set at least, you could do:

$missingValue = TRUE;

if(isset($_POST['checkbox_foo'] || isset($_POST['checkbox_bar'])
{
    $missingValue = FALSE;
}

If that's not good enough, you'll have to go with hidden fields.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.