Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run through each checked checkbox with a classname using JavaScript without jQuery

Is there an immediate equivalent in javascript for the below jquery code?

$('.checkbox').each(function() {
    if ($(this).is(':checked')) {
        //logic here
    }
});

I'm trying to run through all the checkboxes on a page with class = 'checkbox' - the client doesn't want to use jQuery, so I need an alternative for the above.

I'm hoping I can avoid writing a long function from scratch to do this and simply use something built-in to JavaScript, but it's looking like it's not possible.

like image 654
korben Avatar asked Dec 13 '22 08:12

korben


1 Answers

Many older browsers don't support querySelectorAll or getElementsByClassName, so you'd have to loop over all <input> elements in those browsers. It's always best to check for those functions first, though.

Secondly, you should never use $(this).is(":checked")not even in jQuery — it's a very slow path to take when looking for this.checked.

This should get you going:

var base = document,
    inps, tmp, i = 0, reg = /\bcheckbox\b/;

// getElementsByClassName is the fastest method
if (base.getElementsByClassName)
    inps = base.getElementsByClassName("checkbox");
// Followed by querySelectorAll
else if (base.querySelectorAll)
    inps = base.querySelectorAll(".checkbox");
// But if neither exist, loop through all the elements and check the class
else {
    inps = [];
    var tmp = base.getElementsByTagName("input");
    i = tmp.length;
    while (i--) {
        if (reg.test(tmp[i].className)
            inps.push(tmp[i]);
    }
}

// Finally, loop through the matched elements and apply your logic
i = inps.length;
while (i--) {
    var current = inps[i];
    if (current.checked) {
        // logic here
    }
}

In the example above, you can change the value of base to any element. This means that, if all these elements have a common parent or ancestor node, you can set that element as the base and it should run faster, e.g:

var base = document.getElementById("myForm");
like image 171
Andy E Avatar answered Dec 22 '22 00:12

Andy E