-1

I have an input of checkboxes as an array:

<input type="checkbox" name="checkbox[]">

And I want to send the unchecked checkboxes as well. So if it's unchecked I want it to be in the array as well

I tried the solution in this post: POST unchecked HTML checkboxes:

  <input type='hidden' name='checkbox[]'>
  <input type='checkbox' name='checkbox[]'>

However, in the post it's not an array of checkboxes. In my case it doesn't work, it just adds it to the array and not overriding it.

So if I have a list of 5 checkboxes where 2 of them has been checked, I'll end up with 7 total of POST parameters (5 from the hidden, and 2 from the checkbox)

pileup
  • 1
  • 2
  • 18
  • 45
  • 1
    The point of having only checked ones in the submitted data is that you can tell which ones are checked and (by the implication of them not being there) which are not. What's the point of having checkboxes at all if they are all going to appear in the submitted data regardless? – Quentin Oct 24 '22 at 13:01
  • Because of the way the code was written in the past, they rely on the order of the inputs and each parameter is an array of the other inputs, related by the `key` of the array. So I need to have matching array of checkboxes to the other inputs (So the checkbox in the array of checkboxes with key 5 should match some `textarea` with key 5 in the `textarea` input array – pileup Oct 24 '22 at 13:03

1 Answers1

1

Your comment reveals that this is an XY problem.

Because of the code was written in the past, they rely on the order of the inputs and each parameter is an array of the other inputs, related by the key of the array. So I need to have matching array of checkboxes to the other inputs

Give the checkboxes and related other inputs explicit keys in the data PHP generates from the form submission.

<input type="checkbox" name="checkbox[316]">

It is common to use the row id of a database table for this.

That will maintain the association of the checkbox data with the rest of the inputs in the same set without including unchecked checkboxes.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks! I think it's getting closer then to a solution (I will have to deal with the XY problem in this case later as I did not originally wrote the code and I can't change it now). The problem is that the default keys that are used now are the tables rows (These inputs are output by PHP in a `foreach` loop. So I will need to use some `counter` inside the PHP loop and put it inside the checkbox array. But is it possible to put a PHP variable inside the `checkbox[]` array? like `'checkbox[$counter]'` somehow? – pileup Oct 24 '22 at 13:11
  • 1
  • That's working, thank you! I love how you figured both the issues in this case without me explicitly saying. And yes, this entire code piece has another big issue which will be taken care of as soon as I can – pileup Oct 24 '22 at 13:15