Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  12] [ 4]  / answers: 1 / hits: 7258  / 11 Years ago, wed, february 12, 2014, 12:00:00

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()>

More From » html

 Answers
9

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).


[#47820] Tuesday, February 11, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sashacitlallik

Total Points: 30
Total Questions: 100
Total Answers: 85

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
;