0

I have this weird bug occuring when a function name is the same as an input name :

<script>
  function sameName() {
    console.log("Clicked sameName")
  }

  function sameName2() {
    console.log("Clicked sameName2")
  }
</script>
<form>
  <input type="text" id="sameName" />
  <input type="button" value="bug" onclick="sameName()" />
</form>

<input type="text" id="sameName2" />
<input type="button" value="no bug" onclick="sameName2()" />

In order to reproduce the bug :

  • the function and the input text must have the same name
  • the input text and button have to be in the same form

Is there a mistake in my code or is it a bug?

Thanks

edit : thanks to VLAZ, I saw that it's not a jquery related bug, But I still don't understand why there is an error only when it involves two inputs in a form. There's no error if the input text is switched for a div for example.

Phil
  • 157,677
  • 23
  • 242
  • 245
CharlesM
  • 19
  • 4
  • 2
    The problem is that elements with IDs get put on the `window` object. It's not jQuery - it's the standard for browsers. – VLAZ Aug 17 '21 at 06:28
  • thx for your answer. Why is there no error if the inputs are not in a form? – CharlesM Aug 17 '21 at 06:34
  • 1
    ¯\\_(ツ)_/¯ You really shouldn't write code like this anyway. Inline event handlers in the HTML have different and some times surprising rules due to how they are executed. My guess is it's because of something there. But to be quite honest, I don't care. I find these tricky little implementation details useless. I can think of weird bugs that are due to weird legacy behaviour far easier than what I had for breakfast. And that bothers me. I'd rather not expand my knowledge of bugs that shouldn't exist at the expense of my more of my sanity. – VLAZ Aug 17 '21 at 06:49
  • Did some debugging and found that inline event handlers on form controls (inputs, buttons, etc) within a `
    ` execute in the context of the `HTMLFormElement`. For example, if you directly add a function on the form (eg `formEl.foobar = () => { console.log("form.foobar") }`), you can use `onclick="foobar()"` on the controls. So because forms include their named / id'd controls as dot-properties, that is why you get this error
    – Phil Aug 17 '21 at 06:57
  • thx Phil, it seems that you've identified the cause of this problem – CharlesM Aug 17 '21 at 07:10

0 Answers0