I'm trying to add script to my html form that will remove all unchecked checkboxes and replace them with a hidden field and a value of "no". If checkboxes are checked, they will show a value of "yes".
Please note, I can not add this hidden field into the form because the site I host it on does not allow two form fields with the same name, as I've seen suggested before: Post the checkboxes that are unchecked
For some reason, the script only works when I load the page, submit the form with all checkboxes unchecked, then submit the form again. If I reload the page, I have to do the same thing again. This shows what I'm referring to: https://gfycat.com/HarshWaterloggedKestrel
Is it because I'm adding the event listener after the first form submission?
Here is a fiddle with sample code: https://jsfiddle.net/gvd1jr0o/6/
Here is my script:
$("#foo").submit(
function() {
var formEl = $(this);//get the reference of the form
debugger;
// Add an event listener on #foo submit action...
// For each unchecked checkbox on the form...
formEl.find("input:checkbox:not(:checked)").each(
// Create a hidden field with the same name as the checkbox and a value of 0
// You could just as easily use "off", "false", or whatever you want to get
// when the checkbox is empty.
function(index) {
var input = $("<input>");
input.attr('type', 'hidden');
input.attr('name', $(this).attr("name")); // Same name as the checkbox
input.attr('value', "no"); // or 'off', 'false', 'no', whatever
// append it to the form the checkbox is in just as it's being submitted
formEl.append(input); //$("#foo") is referring to the form
} // end function inside each()
); // end each() argument list
return true; // Don't abort the form submit
} // end function inside submit()
);