I've got a load of checkboxes that are checked by default. My users will probably uncheck a few (if any) of the checkboxes and leave the rest checked.
Is there any way to make the form POST the checkboxes that are not checked, rather than the ones that are checked?
I would prefer collate the $_POST
it minds, if the POST doesn't have have the 'checkboxname'value, it was unckecked so, asign a value.
you can create an array of your ckeckbox values and create a function that check if values exist, if doesn`t, it minds that are unchecked and you can asign a value
This can solely be accomplished with some javascript, as unchecked checkboxes don't get transmitted. So you need javascript that e.g. behind the scenes adds hidden fields on unchecking a checkbox. Without javascript this could not be done.
This solution is inspired by @desw's one.
If your input names are in "form style", you will lose array index association with your chekbox values as soon as one chekbox is checked, incrementing this "dissociation" by one unit each time a chekbox is checked. This can be the case of a form for inserting something like employees composed by some fields, for instance:
In case you insert three employees at once and the first and the second ones are single, you will end up with a 5-element
isSingle
array, so you won't be able to iterate at once through the three arrays in order to, for instance, insert employees in a database.You can overcome this with some easy array postprocessing. I'm using PHP at the server side and I did this:
@cpburnz got it right but to much code, here is the same idea using less code:
JS:
HTML (note the field name using an array name):
And for PHP:
I would actually do the following.
Have my hidden input field with the same name with the checkbox input
and then when i post I first of all remove the duplicate values picked up in the $_POST array, atfer that display each of the unique values.
I got this from a post remove duplicate values from array
So this solution is overkill for this question, but it helped me when I had the same checkbox that occurred many times for different rows in a table. I needed to know the row the checkbox represented and also know the state of the checkbox (checked/unchecked).
What I did was to take the name attribute off of my checkbox inputs, give them all the same class, and create a hidden input that would hold the JSON equivalent of the data.
HTML
Javascript to run on form submit
The json string will get passed with the form as $_POST["has-permissions-values"]. In PHP, decode the string into an array and you will have an associative array that has each row and the true/false value for each corresponding checkbox. It is then very easy to walk through and compare to current database values.