Reputation: 41
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
Reputation: 10189
Use onkeypress
on document
using pure javascript:
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:
.js
extension<script src="your_filename.js" type="text/javascript"></script>
before your closing </body>
tag.Upvotes: 4
Reputation: 1833
With the help of jQuery:
$(document).keydown(function(e) {
if (e.keyCode == 13) {
$('#your-form').submit();
return false;
}
});
Upvotes: 1