meles
meles

Reputation: 456

Post the checkboxes in an array that are unchecked

I want to get all values from a set of checkboxes via POST - also the ones that return false. For a single checkbox there is a solution here. It's hacky but it does at least not require Javascript. But how about this

<input name="link[]" type="checkbox"/>
<input name="link[]" type="checkbox"/>
...

A similiar solution as the one suggested in the other post would not work, because it keeps iterating:

<input name="link[]" type="hidden"/>    <!-- 0 -->
<input name="link[]" type="checkbox"/>  <!-- 1 -->
<input name="link[]" type="hidden"/>    <!-- 2 -->
<input name="link[]" type="checkbox"/>  <!-- 3 -->
...

Upvotes: 0

Views: 997

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65883

When a form is submitted, all the form elements that have a name attribute specified for them submit their name and their value. With most form elements, the value comes from what the user inputs.

When you submit a form that has radio buttons and/or checkboxes in it, only the name/value pairs form the checked checkbox or radio button is submitted. This way, your form processing code doesn't have to sort out which buttons/boxes were checked. A consequence of this however, is that both checkboxes and radio buttons must have a value set for their value attribute. This value is how you will know which button/box was selected (receiving a name/value pair of checkbox4=true doesn't really tell you much.)

In the following code, we will know which checkboxes were checked just by looking at the data submitted to the form's action which checkboxes were checked and what the meaning of those checks were:

<input type="checkbox" name="chkStudent1" value="Mary"> Mary
<input type="checkbox" name="chkStudent2"  value="John"> John
<input type="checkbox" name="chkStudent3"  value="Joe"> Joe

Now, when the form is submitted, and let's say you check the second checkbox, the name/value pair of chkStudent2=John will be submitted. Your form processing code will know exactly which element was checked and the corresponding data will be available to that code.

Upvotes: 0

Hissvard
Hissvard

Reputation: 474

The one other way I can think of is explicitly giving them indexes

<input name="link[0]" type="hidden"/> 
<input name="link[0]" type="checkbox"/>  
<input name="link[1]" type="hidden"/>   
<input name="link[1]" type="checkbox"/>
<input name="link[2]" type="hidden"/>
<input name="link[2]" type="checkbox"/>

Or you could do this, without using hidden inputs:

<input name="link[0]" type="checkbox"/>  
<input name="link[1]" type="checkbox"/>
<input name="link[2]" type="checkbox"/>

Then check for missing array indexes server-side.

Upvotes: 2

Related Questions