I just realized that inside a form event handler (like onsubmit
or oninput
etc), you can access control values globally, meaning the following does indeed work:
<form onsubmit="alert(theInput.value); return false">
<input name="theInput">
</form>
Why does this work? I never defined theInput
anywhere and it is also not a global variable.
Assuming that the internal browser code assigns those variables itself, why cant I access theInput
in a custom event handler?
function submitHandler() {
alert(theInput.value)
}
<form onsubmit="submitHandler(); return false">
<input name="theInput">
</form>
In submitHandler()
, theInput
is undefined and the code breaks, as I expected.
Is there any documentation available about this? Could not find any, but it is admittedly something hard to search for. MDN docs even use this syntax in one of their examples.
This could help you:
3 solutions:
Read more here, hope it helps you, Cheers!
http://www.howtocreate.co.uk/referencedvariables.html
It seems that the browser is assigning
theInput
behind the scenes. The reason it's not working in your second case is because you're looking fortheInput
in the scope of thesubmitHandler
function, not the scope of the actual event handler. It works if you passtheInput
intosubmitHandler
in your HTMLonsubmit
, even if you change the variable name insubmitHandler
.Furthermore, it fails if you change
submitHandler(theInput)
to something else, see below:Inline handlers (unintuitively) appear to run inside a
with(this)
, wherethis
is the element that the handler is on:The
document
is alsowith
ed as well.From a
<form>
, you can access an input with a particular name via dot notation, so referencingtheInput.value
works just like referencingthis.theInput.value
in the inline handler.Solution: Never use inline handlers, they're crazy.