user1325927
user1325927

Reputation: 59

Javascript that submit a form when pressing the ENTER

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?

Upvotes: 0

Views: 5286

Answers (3)

ltiong_dbl
ltiong_dbl

Reputation: 3216

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)

Upvotes: 1

Alkis
Alkis

Reputation: 49

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?

Upvotes: 0

Jason Barry
Jason Barry

Reputation: 758

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.

Upvotes: 1

Related Questions