Wednesday, July 2, 2008

Unchecked checkbox values


Great! Solved my problems!



http://iamcam.wordpress.com/2008/01/15/unchecked-checkbox-values/






Working with form check boxes can be a bit of a pain on sites with dynamic content. Saving the checked data is easy, but how do you easily save the unchecked value without manually adding it to an array from inside your code? Keep reading.


revealCMS is working great - I’m really starting to see a lot of its strengths (and, admittedly, some weaknesses) as I use it more and begin extending it. Due to how data is saved to the database, the HTML checkboxes were a bit of a problem when trying to save their unchecked state. Typically I save the post data to the object, where it is filtered and scrubbed, as necessary.<i>Only the posted values get updated</i> in their respective rows (makes sense, right?).


The problem is that unless a box is checked, it’s not going to be sent with the form - a problem if you have a checked box, but want to save the unchecked state.The first option is easy and probably the first solution you’d think of - write a couple lines of code for every single checkbox and set it to some default value if it’s left unchecked when the form is posted. Fine, but that takes more thinking than I want to do for something so simple, and it’s somewhat prone to error. Instead…


…the solution: Insert a hidden form field with the same name as the checkbox and the default value right before the place where the checkbox is located:









 









What happens here is that when the checkbox is left unchecked, the hidden field’s value gets submitted, as-is. When the check box is checked, the hidden field’s POST value gets overwritten by the activated checkbox’s.

Unactivated: Hidden field’s value.

Activated: Check box’s value.


Told you it was easy!








If you know what you are expecting your POSTed data to be, which you should as you made the HTML form, then just create a new array from the POSTed one.


You need to name the keys of the checkbox name array:

EG


When the form is posted, make a new array using ALL the key names you KNOW are used in the checkbox names


Then use that new array to loop all keys. With each loop, check if the current key from your new array matches a key in the posted array.

If no match then that key value is NO, if it is matched then that key value is YES.

It’s IMPORTANT when you make the new array to make the keys in the same order as they appear in the html form or the loop wont match them in order and wont work correctly


Here is the full script


form.html page






 

No comments:

Post a Comment