How to get checkbox value in form submission

checkbox html html5 checkbox value

Suppose you have a checkbox in your HTML form like this:

Email Address:
<input type="email" name="email">

<input type="checkbox" name="opt_in_newsletter" > Subscribe to the newsletter

If the user checks the option, you will get the following form data


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.

You might have expected opt_in_newsletter=off But in reality, the behavior is different the W3c recommendation supports this behavior by the way.

In the server-side code, just check for the presence of the field first.

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:

  <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>

If the user selects the option, form data will contain: send_newsletter=yes else, the form data will contain send_newsletter=no

See Also