In order for the backend to receive something, your checkbox must be in the checked
state and it must have a name . If you do not set attribute value
, by default it will send the value on
when it is checked. But to simplify things, let's put value 1.
<input type="checkbox" name="micampo" value="1">
When checked, the backend receives 1. When it is not checked, the backend receives nothing, as if the checkbox did not exist.
Therefore, the most common technique is to put an input of type hidden
with the same name, which if the checkbox is deactivated, that input is responsible for sending a zero, false or off to the backend.
<input type="hidden" name="micampo" value="0"/>
<input type="checkbox" name="micampo" value="1"/>
This can be proven in the example below. Take into account that in that serialization, the last one that declares the value of a name is the one that is valid, so that
backend.php?micampo=0&micampo=1
Equivalent to
backend.php?micampo=1
jQuery('#comprobar').on('click',function() {
console.log('Voy a enviar',jQuery('#miformulario').serialize());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="miformulario">
<input type="hidden" name="micampo" value="0"/>
<input type="checkbox" name="micampo" value="1"/>
<input type="button" id="comprobar" value="comprobar"/>
</form>
Regarding the "component" the switch is really just a cosmetic effect that adds materialize. Your checkbox is still as it is, but invisible.
PS: this can obviously be done without jQuery, but materialize by itself has jQuery as dependency.