qua1ity
qua1ity

Reputation: 623

JavaScript - checkboxes and events

How do i trigger an event when an input of type="checkbox" is checked? For buttons i simply create an addEventListener with the event 'click'. Is there a similar way of doing this with checkboxes?

For example i have two containers, both containing a checkbox and a div element. When one of the checkboxes is "checked", then i want their div element (box) to change color or something like that. And then go back to its first state when its unchecked.

<div class="boxCont">
    <input type="checkbox" class="checkbox">
    <div class="box"></div>
</div>

<div class="boxCont">
    <input type="checkbox" class="checkbox">
    <div class="box"></div>
</div>

Example: https://jsfiddle.net/qua1ity/vs64yyrv/1/

Is this possible with JavaScript, without changing the HTML?

Upvotes: 1

Views: 447

Answers (1)

Sidd
Sidd

Reputation: 1397

For checkboxes, you can use onchange instead of onclick, and inside the function check if the value of this.checked is true or false.

Here is a fiddle: https://jsfiddle.net/vs64yyrv/2/

I used [].slice.call() to be able to use forEach instead of a loop, since I wanted to alert which checkbox has been clicked, and you can't use event handlers inside loops without losing the count value. If you don't need that index, you can simply use

var checks = document.querySelectorAll('.checkbox');

for(var i=0;i<checks.length;i++){
    checks[i].onchange = function(){
        if(this.checked) {
            //do your thing with `this`
        }
        else {
            //return to previous state
        }
    } // end handler
} // end loop

Upvotes: 1

Related Questions