0

I have a form that the client can fill in with some info. It also has some checkboxses that the backend handles. When I submit the checkbox as unchecked I have noticed that its not even sent with the post so when the backend handles the form values, the checkbox's name doesn't exist and is undefined.

My question is why checkboxses are ignored when the form is posted if its unchecked? How could I fix it so It either sends true or false as the value when posting the form depending on if the checkbox is checked or not?

Here is an example bit from my form that I have on my clientside:

<form method="POST" action="example.com/api/">
    <input type="checkbox" id="example_checkbox" name="example_checkbox" value="false" checked>
    <button class="btn btn-primary" type="submit">Submit</button>
</form>

I also have some jquery which sets the value of the checkbox in the html to false or true depending on if the client checks the checkbox or not:

$('#useRandomPassword').on("change", function() {

    if ($('#useRandomPassword').is(":checked")) {
        $('#useRandomPassword').val(true);
    } else {
        $('#useRandomPassword').val(false);
    }

})
Linus J
  • 178
  • 1
  • 2
  • 10

2 Answers2

1

An unchecked checkbox is skipped when constructing form data due to the HTML specification https://www.w3.org/TR/html50/forms.html#constructing-form-data-set and it has been that way for a long time.

Option 1:

Add a hidden field with the same name and a falsy value when the field is unchecked using Javascript.

Option 2:

Add a hidden field to specify that the checkbox field is being submitted. This can be useful in some cases where you may want to exclude processing if the checkbox isn't part of the submission.

Ralph Ritoch
  • 3,260
  • 27
  • 37
0

Checkboxes values aren't sent at all to the backend when they are not checked. I don't know if there's a good reason for this, but it's just the way it is.

The way to check for a checkbox is to just see if some value was returned. For example, using php, you would just do:

isset($_POST['example_checkbox'])

This will return true if the checkbox has sent somenthing back, and false if it didn't.

If for some reason you don't like this, and you want to "fool" the form to submit a value when the checkbox is not checked, you can take a look at this

clod9353
  • 1,942
  • 2
  • 5
  • 20