Suppose you have a checkbox in your HTML form like this:
<form>
Email Address:
<input type="email" name="email">
<input type="checkbox" name="opt_in_newsletter" > Subscribe to the newsletter
</input>
If the user checks the option, you will get the following form data
email=name@domain.com
opt_in_newsletter=on
However, if the user does not check the option, then the opt_in_newsletter field itself will not be present in the form data that you receive on the server-side.
email=name@domain.com
You might have expected opt_in_newsletter=off But in reality, the behavior is different the W3c recommendation supports this behavior by the way.
You can test this behaviour in the form below. The code below uses the service show.ratufa.io to display the values received on the server side. (note that the action field of the form is set to show.ratufa.io ) If you do not select the checkbox, there will not be any value corresponding to the checkbox in the data received on the server side.
Solutions
One solution is to check for the presence of the value on the server side.
Another alternative is update the form data before sending to the server, using Javascript.
The workaround using hidden fields
In case you want a definite value for each input on the server-side is to use hidden fields along with checkbox. Both fields should have the same name.
Here is an example:
Here is the relevant code for better reference:
<div>
<input type="hidden" name="send_newsletter" value="no">
<input type="checkbox" name="send_newsletter" id="send_newsletter" value="yes" />
<label for="send_newsletter">Subscribe to the newsletter</label>
</div>
If the user selects the option, form data will contain:
send_newsletter=yes
else, the form data will contain send_newsletter=no
See Also
- How to Create a Telephone Input Field in HTML5
- How to Use Html5 Input Type Email
- Checkbox checked validation using JavaScript
- Checkbox validation using jQuery
- Custom styled checkboxes with Bootstrap
- HTML Form Checkbox with required validation
- HTML Form with Checkboxes examples and sample code
- How to create a dropdown with checkbox options with Bootstrap Style
- How to create checkbox in Bootstrap style ?
- How to do multiple checkbox validation in Javascript