Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - Trigger event when any checkbox is checked/unchecked

Tags:

javascript

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

like image 283
chris97ong Avatar asked Dec 14 '22 23:12

chris97ong


2 Answers

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

like image 141
beeglebug Avatar answered May 01 '23 07:05

beeglebug


Clicks are bubbling through the document, you could use a single eventlistener for the parent element of these inputs. 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.

like image 45
Teemu Avatar answered May 01 '23 07:05

Teemu