Making checkboxes pass data even when they are unchecked
Web pages don't normally send back any data for checkboxes that are unchecked. This Javascript function fixes that.
You call the function any time the page has completed loading or when you add more elements to the page.
It works by renaming the checkbox and creating a new hidden field using the checkbox's original name. Then when the checkbox is checked or unchecked, the proper value is set in the hidden field.
function enhance_checkboxes() { $("input[type=checkbox]").each(function() { if($(this).data("orig_name")==undefined || $(this).data("orig_name")=="") { var orig_name=$(this).attr("name"); // get the name of the checkbox if(orig_name==undefined) { $(this).data("orig_name","undefined"); // so we don't keep processing this checkbox } else { $(this).attr("name",orig_name+"_real_checkbox"); // rename the checkbox $(this).data("orig_name",orig_name); // store the name of the hidden field $(this).after("<input type='hidden' name='" +orig_name+"'>"); // create the hidden field $("input[name="+$(this).data("orig_name")+"]").val($(this).prop("checked")?$(this).val():""); // initialize the hidden field $(this).on("change",function() { $("input[name="+$(this).data("orig_name")+"]").val($(this).prop("checked")?$(this).val():""); }); } } }); }
Published: 10/06/2020