HTML checkbox submit a value if not checked using JQuery

HTML checkboxes are horrible. If they are checked – they will submit a value, but if they aren’t checked then the the whole input is just left out. This is terrible if you want a value other than null sent. So for example if I want any value besides null set – maybe another default value then I’m stuck trying to hack around this issue.

Here is a simple hack using JQuery to set a value for a checkbox input if it isn’t checked.

It requires creating two inputs, a checkbox input with an id BUT no name value and a hidden input with the name of the value you want to submit.

For this example I have an input that is checking if users want to receive notifications. I have multiple values that the notifications variable can be set to. I want it to be set to 1 if it is unchecked and 2 if they check the box.

 Receive Email Notifications (msgs - news etc).

Now for the JQuery


So the checkbox is ‘checked’ by default – so that means I have to set my value of my hidden field to 2. The checkbox element has an id of ‘notification’. When the user clicks the element it triggers the jQuery click function for ‘notification’. It looks at the element and if it is checked it sets the value of the hidden field – ‘notifications’ to 2 and if it isn’t checked it sets the value to 1.

This might seem a bit clunky, but even though a checkbox has two possible values, html only allows it to submit 1 value. Using this method, you can send any value you want by assigning the actual named variable value through as a hidden input.

You may also like...