A checkbox is only considered to have a value when it is checked. Otherwise, it is not included in the submitted form data.
From the MDN website:
Note: If a checkbox is unchecked when its form is submitted, there is no value submitted to the server to represent its unchecked state (e.g. value=unchecked); the value is not submitted to the server at all. If you wanted to submit a default value for the checkbox when it is unchecked, you could include an <input type="hidden">
inside the form with the same name
and value
, generated by JavaScript perhaps.
A trick to circumvent this limitation is to include a hidden input with a default value. E.g.
<input name="mfa" type="hidden" value="0">
<input name="mfa" type="checkbox" value="1">
With this approach, a value for mfa
will always be submitted with the form data.
I have the following HTML code within a form and the top one (policy) sends in post but the second one does not (mfa). I’m lost at why this is happening, any ideas?
<label class="switch switch-flat">
<input class="switch-input" type="checkbox" id="policy" method="post" name="policy" <?php if($row['policy'] === '1') echo 'checked="checked"';?> />
<span class="switch-label" data-on="Yes" data-off="No"></span>
<span class="switch-handle"></span>
</label>
<label for="policy">Does the vendor organization have a written Information Security policy?</label>
</td>
</tr>
<tr>
<td>
<div class="col-md-12">
<label class="switch switch-flat">
<input class="switch-input" type="checkbox" name="mfa" id="mfa" method="post" <?php if($row['mfa'] === '1') echo 'checked="checked"';?> />
<span class="switch-label" data-on="Yes" data-off="No"></span>
<span class="switch-handle"></span>
</label>
<label for="mfa">Do they support and utilize multi-factor authentication?</label>
</td>
Here’s my ajax to send the post data. When I browse in the Dev tools for headers being sent I see a lot of the other HTML names going but most of the ones listed as toggle checkboxes aren’t being sent except for the top one ‘policy’.
<script type='text/javascript'>
/* attach a submit handler to the form */
$('#update').submit(function(e){
e.preventDefault();
$.ajax({
url:'updateVendor.php',
type:'post',
data:$('#update').serialize(),
success:function(){
//whatever you wanna do after the form is successfully submitted
}
});
});
</script>