0

I try to run the following code in Javascript :

function test(){
    if(document.querySelector('.js-pricing')){
        var checkbox = document.querySelector(".js-pricing");
        alert('is working');
        checkbox.addEventListener('change', function(){
            if(this.checked) {
                console.log('is-checked')
            } else {
                console.log('is not')
            }
        })
    }
}
test();

to know when my checkbox is checked or not, the EventListener is not working I have none console.log in my console but my alert() is working well, I guess the element is well detected when the page is loaded but can't handle the event listener.

Also tried with document.ready to start the event but it does not work I have the same result when I try with a getElementById.

Here is my html (in jade) line for the input :

input(type="checkbox", name="pricing", id="pricing", checked).switch__input.js-pricing 

Do you know how to run the EventListener properly?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Damien Compère
  • 219
  • 1
  • 3
  • 16
  • Your code will hook up a `change` handler to the **first** element in the DOM that has the class `js-pricing` as of when you run `test`. That handler will be called when the `change` event for that element is fired, which will be if it's an `input`, you change its value, and (in some cases) if you move off the input making it lose focus (`change` isn't fired until you lose focus for some `input`s). If you're not seeing that, then A) The element isn't in the DOM yet when you run `test` (see [answers here](https://stackoverflow.com/questions/14028959/)) or B) The first element *(cont'd)* – T.J. Crowder Nov 15 '19 at 17:12
  • *(continuing)* with that class isn't an `input`, or C) You're not changing the value and taking focus away from the element. If you have multiple elements with that class, [this question's answers]( B) http://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) show you how to hook up multiple elements. – T.J. Crowder Nov 15 '19 at 17:14
  • Humm I think my issue is different because it seems that the element is detected when the page is loaded but not on the event, I edited my post with an alert() that works – Damien Compère Nov 17 '19 at 13:48

0 Answers0