Catching form onSubmit vs catching Enter key?
forms, html, javascript
Solution
My gut instinct is to use a form and onSubmit
sounds like your gut is in tune with common practice. ;-)
which has the advantage of handling unique submission methods on the browser level
Which makes it robust and reliable, perhaps explaining why it is common practice.
but I'm not sure if there are any standards/best practices that discourage that.
Certainly no official standards either way (but it's not their job to do that either). "Best" is a relative term based on criteria for making comparisons. If your criteria include things like: robustness, ubuiquitous support, ease of maintenance and simplicity then putting a submit listener on the form will likely rank very highly.
PS: For a form control to be successful (i.e. for its value to be submitted with the form), it must have a name. An ID is optional (and usually not required).
Problem
I have a page that involves a textbox and a button, with JavaScript functionality that triggers when a user clicks on the button. I'd like the functionality to also be triggered when the user presses the Enter key. What I'm not sure about is whether to make the two inputs into a form and use "return functionname()" in the onSubmit attribute, or to capture pressing the Enter key in the textbox. My gut instinct is to use a form and onSubmit, which has the advantage of handling unique submission methods on the browser level, but I'm not sure if there are any standards/best practices that discourage that. That is: ``` <form id="myform" onsubmit="return myFunction()"> <input type="text" id="mytextbox"> <input type="submit" id="mysubmit" value="Go"> </form> ``` vs ``` <input type="text" id="mytextbox" onkeypress="myFunction()"> <input type="button" id="mysubmit" value="Go" onclick="myFunction()"> ```