I am trying to add a script to my html form that will remove all unchecked checkboxes and replace them with a hidden field and a no. If the checkboxes are checked, they will show the value yes.
Please note: I cannot add this hidden field to the form because the site I host it does not allow two form fields with the same name as before: Post checked checkboxes
For some reason, the script only works when the page loads, submit the form with all the checkboxes checked, and then submit the form again. If I reload the page, I must do the same again. This shows what I mean: https://gfycat.com/HarshWaterloggedKestrel
Is it because I add an event listener after submitting the first form?
Here is a fiddle with sample code: https://jsfiddle.net/gvd1jr0o/6/
Here is my script:
$("#foo").submit(
function() {
var formEl = $(this);
debugger;
formEl.find("input:checkbox:not(:checked)").each(
function(index) {
var input = $("<input>");
input.attr('type', 'hidden');
input.attr('name', $(this).attr("name"));
input.attr('value', "no");
formEl.append(input);
}
);
return true;
}
);
source
share