I'm usig this code from Required attribute on multiple checkboxes with the same name? by Zhomart.
It works great when you enter a new entry, but if used on an edit/modify form (that loads data from a database) they require you to check a checkbox, even if the form already has (at least) one checkbox checked. Could you suggest how to modify the script so that it also consider if at least one checkbox with the same id/name is already checked? Thanks!!
Here is the code:
$(function(){
var allRequiredCheckboxes = $(':checkbox[required]');
var checkboxNames = [];
for (var i = 0; i < allRequiredCheckboxes.length; ++i){
var name = allRequiredCheckboxes[i].name;
checkboxNames.push(name);
}
checkboxNames = checkboxNames.reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);
for (var i in checkboxNames){
!function(){
var name = checkboxNames[i];
var checkboxes = $('input[name="' + name + '"]');
checkboxes.change(function(){
if(checkboxes.is(':checked')) {
checkboxes.removeAttr('required');
} else {
checkboxes.attr('required', 'required');
}
});
}();
}
});`
CODE FOR REQUIRED PLUS AUTO-CHECK This code allows to extend the required to checkboxes that autocomplete:
$(document).ready(function (){
$("#date").on('change', function(){//look at enter/change date
for (var i = 1; i < 8; ++i){ //this removes previusly checked days
document.getElementById("courseweekday"+i).checked = false;
}
var weekdaynumber = $( "#weekdaynumber" ).val(); //get value of box id that needs to be checked
document.getElementById("weekday"+weekdaynumber).click(); //check box with relative id
});
});
Only problem, that the required attribute doesn't work anymore if the checkbox (after auto-checked) is manually unclicked.
Just removing the Change event handler on the above code will work on load of the document. Place this code after your last for loop
for (var i in checkboxNames){
!function(){
var name = checkboxNames[i];
var checkboxes = $('input[name="' + name + '"]');
if(checkboxes.is(':checked')) {
checkboxes.removeAttr('required');
} else {
checkboxes.attr('required', 'required');
}
}();
}
NOTE: I have removed the change event handler. Everything else is the same code.
working JS fiddle https://jsfiddle.net/RajReddy/yf17eL3p/3/