user2568916
user2568916

Reputation: 41

Map enter key to submit while not inside input

I have a form with multiple input boxes that I'm trying to get to submit when I press the enter key, regardless of whether or not one of the inputs is currently highlighted. That is, I want to be able to enter text, click the background of the page, hit enter, and have the form submitted. I have tried making a hidden button, but this solution only appears to submit when the cursor is inside one of the inputs.

Upvotes: 4

Views: 1362

Answers (2)

Mohammad Areeb Siddiqui
Mohammad Areeb Siddiqui

Reputation: 10189

Use onkeypress on document using pure javascript:

Fiddle.(demo)

JS:

var form = document.getElementById('form');
document.onkeypress = function(e) {
    if(e.keyCode === 13) //if enter pressed
    {
        form.submit();
    }

}

Here's another solution using addEventListener, as suggested by Matt:

var form = document.getElementById('form');
function submitForm(e) {
    if(e.keyCode === 13) //if enter pressed
    {
        form.submit();
    }

}

document.addEventListener('keypress', function() {submitForm(event)}, false);

As a side note: I would discourage you using jQuery on places where pure JS can help you easily that's why gave you a javascript solution. I would discourage that because jQuery increases the load on the server alot!

As you said you are new to javascript do the following steps to get your script running everytime:

  1. Add my code to a file with .js extension
  2. Add <script src="your_filename.js" type="text/javascript"></script> before your closing </body> tag.
  3. Refresh your page and voila.

Upvotes: 4

Pieter
Pieter

Reputation: 1833

With the help of jQuery:

$(document).keydown(function(e) {

    if (e.keyCode == 13) {

         $('#your-form').submit();

         return false;
    }

});

Upvotes: 1

Related Questions