简体   繁体   中英

Obtaining of all values of checkboxes in JavaScript

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?

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. :)

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM