Skip to content Skip to sidebar Skip to footer

Make Html Checkbox Send True / False In Serialization

I have the following checkbox in a form: This is sent to a SpringController via javascript: .ajax({

Solution 1:

You can set the default of the checkbox to be false so that when the form is parsed into an object, it will only be true if the checkbox was checked.

If you want it to be checked by default so that the user doesn't have to click it, you can check the box manually via JavaScript when the page loads.

Solution 2:

You could change the checkbox to a dummy name, and make preparationNeeded a hidden field, and use JS to set the value of preparationNeeded appropriately on every change to the checkbox state.

Solution 3:

One option is to observe clicks on the checkbox and when the checkbox is checked, clear the name on the hidden input. That way the hidden input value will only be added to the serialized output when the checkbox is not checked.

See a demonstration of this below:

$(document).ready(function() {
  $('#serialize').click(serializeForm);
  $('#preparationNeededCheckbox').click(handleCheckboxClick);
});

functionserializeForm() {
  console.log('serialized form: ',$('#updateform').serialize());
}

functionhandleCheckboxClick() {
  $('#hiddenCheckboxInput').attr('name', this.checked ? '' : this.name);
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="updateform">
  Needs Preparation: <inputtype="checkbox"name="preparationNeeded"value="true"id="preparationNeededCheckbox" /><inputtype="hidden"name="preparationNeeded"value="false"id="hiddenCheckboxInput" /></form><buttonid="serialize">Serialize</button>

But perhaps it might be simpler to have two radio buttons- one for true, one for false...

Post a Comment for "Make Html Checkbox Send True / False In Serialization"