In my HTML, I have a lot of checkboxes.
<input type="checkbox"> Check me!
<input type="checkbox"> Check me as well!
<input type="checkbox"> Check me too!
<input type="checkbox"> This is a checkbox.
<input type="checkbox"> It is not a radio button.
<input type="checkbox"> Just saying.
(Even more checkboxes ..............)
Without jQuery, how do I create an alert once any checkbox in the document is changed?
(With so many checkboxes, it will be very troublesome to add onclick="alert('Hello!');"
on every single checkbox.)
This is how you would do it without jQuery:
// get all the checkboxes on the page
var checkboxes = document.querySelectorAll('input[type=checkbox]');
// add a change event listener
for(var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function(){
console.log('the checkbox changed');
});
}
Note: document.querySelectorAll
is not supported in IE7 or below.
http://caniuse.com/queryselector
Clicks are bubbling through the document, you could use a single eventlistener for the parent element of these input
s. Something like this:
<form id="form">
<input type="checkbox"> Check me!
<input type="checkbox"> Check me as well!
<input type="checkbox"> Check me too!
<input type="checkbox"> This is a checkbox.
<input type="checkbox"> It is not a radio button.
<input type="checkbox"> Just saying.
</form>
JS:
document.getElementById('form').addEventListener('click', function (e) {
if (e.target.type === 'checkbox') {
alert('Checkbox');
}
});
If you don't have a form
or any other common parent element (and you don't want to add a one), you can add the listener to the document
as well.
A live demo at jsFiddle.
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