1

I have 11 checkboxes in my HTML form and already have a section in my onclick function to determine how many of them were checked, but I would like to be able to tell which of the checkboxes were checked, and possibly just add whichever checkboxes were checked to an arraylist by id/value etc.

EDIT: (Fixed code..?)

var formobj = document.forms[0];
    var ingNum = 0;
    checked = [];
    for (var j = 0; j < formobj.elements.length; j++) {
        if (formobj.elements[j].type == "checkbox" && formobj.elements[j].checked) {
                ingNum++;
                 checked.push(formobj.elements[j].value);
        }
    } 

2 Answers 2

3

If you want to convert the ones checked to an array of their value attributes (if id attribute, swap value with id), you could use...

var inputs = document.getElementById('your-form').getElementsByTagName('input'),
    checked = [];

for (var i = 0, length = inputs.length; i < length; i++) {
    if (inputs[i].type == 'checkbox' && inputs[i].checked) {
        checked.push(inputs[i].value);
    }
}

That will work on any of the older IEs you may care about.

If you have the luxury of only supporting newer browsers, you could use...

var checked = [].slice.call(document
               .querySelectorAll('#your-form input[type="checkbox"]'))
               .filter(function(checkbox) {
                         return checkbox.checked;
               })
               .map(function(checkbox) {
                        return checkbox.value;
               });

If you were using a library such as jQuery, it's even simpler...

var checked = $('#your-form :checkbox:checked')
              .map(function() {
                      return this.value;  
               })
              .get();
0
0
var checkedBoxes = [];

$("input:checked").each(function() {
    checkedBoxes.push($(this));
});

Actually, I think you could just do this:

var checkedBoxes = $("input:checked");

but I'm not 100% sure if that works.

1
  • Good point, sorry. Still, it could be useful to somebody eventually. :) Apr 7, 2012 at 2:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.