Reputation: 43
I have a html-form with checkboxes. It is required that has been checked by at least one any checkbox. How do I use JavaScript to get the values of all checkboxes, and if there is not one checked among checkboxes then show alert with message?
Upvotes: 0
Views: 90
Reputation: 3240
Since you have tagged this post with jquery
here is a jQuery option.
This function selects all the checkboxes on the page, narrows it down to only the checked ones, then get's the size of the jQuery object.
if ($('input:checkbox').prop('checked').size() == 0)
{
alert('no checkboxes were checked');
}
Hope that helps. :)
Upvotes: 4
Reputation: 169411
// utility function
function toArray(obj) {
var arr = [];
for (var i = 0, len = obj.length; i < len; i++) {
arr[i] = obj[i];
}
return arr;
}
// get the form
var someForm = ...;
// get all elements and check whether any has type "checkbox" and is checked.
var checked = toArray(someForm.elements).some(function (el) {
return el.type === "checkbox" && el.checked;
});
if (!checked) {
alert("please check a box");
}
For browser support use the DOM-shim and the ES5-shim
Upvotes: 0