3

Calling click on an element here via jQuery actually calls it 3 times

This only happens in the latest version of jQuery

$("#a").click()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div>
  <input type="radio" id="a" name="type" checked="checked" value="guest" onclick="alert('a')" />
  <label>A</label>
</div>
<div>
  <input type="radio" name="type" value="guest" onclick="alert('b')" />
  <label>B</label>
</div>

http://jsfiddle.net/2ra0h9ns/3/

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
tony
  • 2,178
  • 2
  • 23
  • 40
  • I have also asked this on the jQuery forums, I'll delete it there if it's not a real issue https://github.com/jquery/jquery.com/issues/216 – tony Mar 04 '21 at 15:35
  • 1
    It works fine (as in, the event is handled once only) when you use a standard jQuery unobtrusive event handler, which is better practice over the inline `onclick`. However I can't explain why the behaviour is happening – Rory McCrossan Mar 04 '21 at 15:36
  • _"This only happens in the latest version of jQuery"_ The latest is 3.6.0 as of yesterday – j08691 Mar 04 '21 at 16:03
  • 1
    Change to `$("#a")[0].click()` and it goes away (doesn't explain why it does it in the first place of course) – freedomn-m Mar 04 '21 at 16:28
  • You can also do document.getElementById("a").click(), and leave jQuery out of it completely – tony Mar 05 '21 at 07:16

1 Answers1

0

Response from jQuery.

"In general, inline event handlers are incredibly hard to work with and should not be used. In nearly all cases, issues involving inline event handlers are out of scope. Inline handlers do not behave the same way as event handlers added with the standard DOM addEventListener method."

https://github.com/jquery/jquery/wiki/Won't-Fix#inline-event-handlers

tony
  • 2,178
  • 2
  • 23
  • 40
  • While not exactly helpful in terms of a diagnosis, this is the best solution. Inline event handlers are archaic and should not be used. – Rory McCrossan Mar 04 '21 at 16:05
  • I found this helpful for the reasons why. As a rule we don't use them, this was legacy code. https://stackoverflow.com/questions/5871640/why-is-using-onclick-in-html-a-bad-practice – tony Mar 05 '21 at 08:07