Why is my click event called twice in jquery?

瘦欲@ 提交于 2019-11-29 01:53:25
T.J. Crowder

If I remember correctly, I've seen this behavior on at least some browsers, where clicking the label both triggers a click on the label and on the input.

So if you ignore the events where e.target.tagName is "LABEL", you'll just get the one event. At least, that's what I get in my tests:

I recommend you use the change event on the input[type="checkbox"] which will only be triggered once. So as a solution to the above problem you might do the following:

$("#toggle").on("change", function(e) {
  if ($(this).is(":checked"))
    console.log("toggle: Show");
  else
    console.log("toggle: Hide");
});

https://jsfiddle.net/ssrboq3w/

The vanilla JS version using querySelector which isn't compatible with older versions of IE:

document.querySelector('#toggle').addEventListener('change',function(){
  if(this.checked)
    console.log('toggle: Show');
  else
    console.log('toggle: Hide');
});

https://jsfiddle.net/rp6vsyh6/

This behavior occurs when the input tag is structured within the label tag:

<label for="toggle"><input id="toggle" type="checkbox" checked>Show</label>

If the input checkbox is placed outside label, with the use of the id and for attributes, the multiple firing of the click event will not occur:

<label for="toggle">Show</label>
<input id="toggle" type="checkbox" checked>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!