Skip to content

Instantly share code, notes, and snippets.

@robertpateii
Last active September 25, 2015 17:38
Show Gist options
  • Save robertpateii/959560 to your computer and use it in GitHub Desktop.
Save robertpateii/959560 to your computer and use it in GitHub Desktop.
a little javascript used to check if a set of checkboxes on your form are checked
// Used to check through an array of checkboxes or radio buttons with the same name attribute.
// max is an integer and is optional. it defaults to 1 if left empty.
function checkBoxesAreChecked(checkboxarray, max) {
var arraymax = max || 1;
var checkedcount = 0;
for (var i=0; i < checkboxarray.length; i++) {
if (checkboxarray[i].checked) {
checkedcount++;
}
}
if (checkedcount > 0 && checkedcount <= arraymax) {
return true;
} else {
return false;
}
}
// If you don't have any validation framework or jQuery, here's some samples to get you through
var validateForm = function (e) {
var e = e || window.event;
if (checkBoxesAreChecked(document.getElementsByName("NameOfCheckboxes")) === true) {
return true;
} else {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
alert("Please select at least 1 option to proceed.");
return false;
}
};
var attachToForm = function () {
var formElement = document.getElementById("form");
if (formElement.addEventListener) {
formElement.addEventListener("submit", validateForm, false);
} else {
formElement.attachEvent('onsubmit', validateForm);
}
};
// If running in <head> here's a basic onload listener.
// Otherwise if running at the bottom of <body> just call attachToForm()
if (window.addEventListener) {
window.addEventListener("load", attachToForm, false);
} else {
window.attachEvent("onload", attachToForm);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment