0

I found a behavior that I don't understand while debugging my JavaScript code.

By having a form element in my HTML, the window.submit JavaScript variable is being automatically populated with a reference to the form's submit button.

I am unfamiliar with this behavior and tried my best to google why the form element is defining the JavaScript variable. Is there part of the HTML spec that describes this behavior?


Live demo - you can see that the variable starts out as undefined, then after the form in the HTML, the variable points to the form's submit button. Why?

<script>
  console.log(window.submit); // Shows "undefined" in console
</script>
<form id="form">
  <label for="message">Message:</label>
  <input type="text" id="message">
  <br>
  <button type="submit" id="submit">Send</button>
</form>
<script>
  console.log(window.submit); // Shows the above "button" element in console
</script>
Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
  • 2
    You are seeing [this behavior](http://stackoverflow.com/a/3434388/139010). – Matt Ball Apr 11 '16 at 21:44
  • 1
    @MattBall Thank you. Just when I thought that JavaScript couldn't get any weirder. Voting to close this as dupe, but hopefully it will stick around in case someone else googles this question the way that I did. – Maximillian Laumeister Apr 11 '16 at 21:47
  • It's not really a duplicate _question_ though... but ok. And it's not really a JS quirk – JS is just a language. It's a weird DOM/HTML thing. – Matt Ball Apr 12 '16 at 02:51
  • @MattBall Eh, it's close enough IMO. Basically the thread you linked answers my question perfectly (thanks again), and duplicate flags are really more about "is this basically the same thing" than "was the exact same question asked". – Maximillian Laumeister Apr 12 '16 at 03:03

0 Answers0