Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my click event called twice in jquery?

Why is my click event fired twice in jquery?

HTML

<ul class=submenu>
    <li><label for=toggle><input id=toggle type=checkbox checked>Show</label></li>
</ul>

Javascript

$("ul.submenu li:contains('Show')").on("click", function(e) {
    console.log("toggle");
    if ($(this).find("[type=checkbox]").is(":checked")) console.log("Show");
    else console.log("Hide");
});

This is what I get in console:

toggle                     menu.js:39
Show                       menu.js:40
toggle                     menu.js:39
Hide                       menu.js:41


> $("ul.submenu li:contains('Show')")
[<li>​                                            ]
    <label for=​"toggle">​
      <input id=​"toggle" type=​"checkbox" checked>​
      "Show"
    </label>​
</li>​
like image 462
shuji Avatar asked Oct 25 '13 16:10

shuji


People also ask

Why is this jquery Ajax click event firing multiple times?

They're attached to buttons for placing a bet, and it works fine for placing a bet on the first hand during a game (firing only once); but in betting for the second hand, it fires the click event twice each time a bet or place bet button is pressed (so twice the correct amount is bet for each press).

How do you make a button click only once in jquery?

You can use jquery . one() This will ensure that the click event happens only once.

What is the difference between .on click function ()) and .click function?

So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.


1 Answers

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:

  • Example with both events | Source
  • Example filtering out the e.target.tagName = "LABEL" ones | Source
like image 133
T.J. Crowder Avatar answered Oct 27 '22 02:10

T.J. Crowder