0

I have a button, the code for which is shown below:

<a href="javascript:document.forms['ContactForm'].submit();" onClick="return ValidateContactForm();" class="button"><span>Submit</span</a>

What JavaScript code do I need so that the form will be submitted when I press the "Enter" key on the keyboard?

Jaimal Chohan
  • 8,530
  • 6
  • 43
  • 64
user1325927
  • 59
  • 1
  • 3
  • 9

3 Answers3

1

You'll need to use "onkeypress" event. Depending on where you want the Focus to be while listening for the Enter keypress..

document.onkeypress = function keypressed(e){
  var keyCode = (window.event) ? e.which : e.keyCode;
  if (keyCode == 13) {
    if(ValidateContactForm())
      document.forms['ContactForm'].submit();
  }      
}

(updated for IE per JavaScript KeyCode Values are "undefined" in Internet Explorer 8)

Community
  • 1
  • 1
ltiong_sh
  • 3,186
  • 25
  • 28
  • Do I need to add a onkeypress to the button - or just should I just place this in the head section of the page and it will work? – user1325927 May 02 '12 at 18:50
  • No, you dont need to put on a button. The code above attaches the event to the document as a whole. you can really put that anyhwere (in a script tag) and it should work. – ltiong_sh May 02 '12 at 19:13
  • Some people are flagging this "not an answer". It may be true, but since the comment system is not suitable for code snippets, please, cut the guy some slack here. – Paulo Scardine Mar 05 '14 at 16:04
1

Just curious, why aren't you using a <input type="submit" /> element? That HTML element automatically submits the form it is nested in when Return is pressed without the need of JavaScript. You can also style it to your heart's content with CSS just like any other element.

Jason Barry
  • 738
  • 5
  • 17
0

Re: ltiong_sh's suggestion The above does not work with Internet Explorer, at least IE8 and below.
For IE8 and below, the following will work:

document.onkeypress = function keypressed(){
  if (window.event.keyCode == 13) {
    // Sumbit code
  }      
}

However, this is not what is important. Important is that this method is very bad:
1) Every keypress is monitored when you are within the input text area or whenever you are in the page (depending on the method used)! (This might steal CPU time)
2) A new page is issued on pressing Enter (or other hot key) with the same URL! That is, the page stacks itself up in history each time Enter is pressed!!!
3) The text within the input area is restored to the default (original one) after pressing Enter!! 4) The submitted text is added to the URL in the address area, as ?

I have not found any way until now to overcome these drawbacks ... (It's the first time today that I'm searching how to press Enter to submit a text (as an alternative to clicking a button).

Is there someone out there to suggest a more effective method?

Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
Alkis
  • 49
  • 5