4

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

3 Answers 3

9

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

you can do like this :

HTML:

<form id="form">
    <input type="checkbox" name="checkbox" /> Check me!
        <input type="checkbox" name="checkbox"/> Check me as well!
        <input type="checkbox" name="checkbox"/> Check me too!
        <input type="checkbox" name="checkbox"/> This is a checkbox.
        <input type="checkbox" name="checkbox"/> It is not a radio button.
        <input type="checkbox" name="checkbox"/> Just saying.
</form>

JS:

var cbobject= document.forms[0].elements.checkbox;
for (var i=0, len=cbobject.length; i<len; i++) {
        if ( cbobject[i].type === 'checkbox' ) {
            cbobject[i].onclick = show_alert;
        }
    }
function show_alert(e){
    alert("checkbox!!!")
}

DEMO:

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.