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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With