Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Submit form when hitting return

form elements

Submit form when hitting return

by  simonchristieis  Posted    (Edited  )
A few people have asked for this functionality recently, so I thought I'd write a FAQ.

first of all we need to tell the page to detect when a key is pressed.
[color red]
window.onkeypress = enterSubmit;

function enterSubmit(){
if (event.keyCode==13)
document.forms(0).submit()
}
[/color]
hey thats great!, but hang on - what if you have form validation on the page?

Using submit() will bypass any onsubmit="return ... statements you have in the form, however you could adapt the function to account for this (assuming formValidation() is your function name):
[color red]
window.onkeypress = enterSubmit;

function enterSubmit(){
if (event.keyCode==13){
if (formValidation())
document.forms(0).submit()
}
}
[/color]

Now we're getting near to some decent functionality, but as you can see the form being submitted is the first form on the page.

How do you overcome this?

Within each form opening tag you could include:

<form name="myForm" onFocus="javascript:document.strForm=this.name">

and change your javascript to:

[color red]
// if no other form has been focussed, submit first form
// on page
document.strForm = 0

window.onkeypress = enterSubmit;

function enterSubmit(){
if (formValidation()){
if (event.keyCode==13)
document.forms(strForm).submit()
}
}
[/color]
Good Luck.

Simon

Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top