We are currently using $('form').serialize()
to get all form information
This will return any checkbox values as "On" or "Off".
Is there any way to get a 1/0 or true/false value using this same method?
Yes. You can do it by adding a hidden input with the same name as checkbox which value will be submitted if checkbox is unchecked:
<input type="hidden" name="option" value="false"/>
<input type="checkbox" name="option" value="true"/>
It will submit both values if checkbox is checked. But server side will read the latest one (value of checkbox)
The value of a form control is always a string. You can use radio buttons to get different values for the same control name:
<form ...>
<input type="radio" name="whatever" value="true">true
<br>
<input type="radio" name="whatever" value="false">false
...
</form>
Only one can be checked, and only the checked name/value will be sent to the server.
If we have multiple checkboxed in our page like :
<input id="reminder" name="Check1" value="false" type="checkbox" />
<input id="alarm" name="Check2" value="false" type="checkbox" />
we have to bind the change event of these checkboxes and set its value to true or false.
$('input[type=checkbox]').on('change', function(){
var name = $(this).attr('name');
if($(this).is(':checked')){
$('input[name= "' +name +'"]').val(true);
$(this).val(true);
}
else{
$(this).val(false);
$('input[name= "' +name +'"]').val(false);
}
});
By default, checkbox value doesn't appear in $('form').serializeArray(), It appears when it is checked.
We have to keep one hidden field for each checkbox like :
<input type="hidden" value="false" name="Check1" />
<input type="hidden" value="false" name="Check2" />
Now when we serialize the form now, we get the correct value like : Check1=true Check2=false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With