Question

I have an checkbox inside of the corresponding label for it.

<div class="list-group-item preference">
   <label for="alertnotices">
      <div class="preference-title">Notices</div>
      <div class="preference-body"></div>
      <input id="alertnotices" class="preference-toggle" name="preference" type="checkbox" data-preference="self.enable.alertnotices">
      <span class="preference-toggle-display"></span>
   </label>
</div>

I have an even listener on the label for when it's clicked to check the state of the checkbox

$.each(document.querySelectorAll('.preference label'), function(idx, toggle) {
    toggle.addEventListener('click', function() {
        console.log(toggle.querySelector('input[name="preference"]').checked);
    });
});

When the label is clicked the previous state and the new state are both logged. I created an example on jsFiddle, http://jsfiddle.net/wuFxt/ I just need the new checkbox state.

Was it helpful?

Solution

check http://jsfiddle.net/WXMHS/

one solution:

just bind to .preference-toggle instaed of label.

why the question example will emit twice? (ps. just my experience, I can't guarantee the reason is right exactly.)

1st emit: clicking the label for="id" tag (except target button itself) will trigger a click event for target button.

2th emit: the label trigger button click event, and then, bubble to the label tag. so that the 2th our label-click-handler has been executed twice.

I wish it could help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top