Zoltán Tamási
Zoltán Tamási

Reputation: 12764

Allow FORM submit on ENTER when focus is not in an input

I have a form where I have a focusable div using tabindex="0". Everything works fine, except for the possibility to submit the form on enter key. It does work when the input is focused, but doesn't when the div has the focus.

I know I could use some javascript to capture the enter key and submit the closest form, but are there any other ways to overcome this?

Here is a little fiddle to demonstrate the problem. https://jsfiddle.net/ajqfm3Lb/1/

Upvotes: 2

Views: 3355

Answers (3)

Tyler Roper
Tyler Roper

Reputation: 21672

Well, instead of submitting the "closest form", you could actually check the Enter keypress for any element within that form. I realize that this is somewhat similar to the solution you weren't looking for, but I'm not sure if you're aware that you can tie that keypress event to specifically the form.

Check it out:

https://jsfiddle.net/ajqfm3Lb/9/

$("form").on("keypress", "*:not(textarea)", function(e) {
    if (e.which == 13) {
        alert("submitted");
        return false;
    }
});

This event only fires when a key is pressed while focus is on the form, because the keypress event is only tied to the selector $("form"). The e.which == 13 just checks enter, specifically.

Of course, you could modify $("form") to be any selector (eg, the form's ID, class, etc).

EDIT: As you pointed out, simply listening for the "enter" press on a form would cause issues with elements that require its use, like textarea. I've used Event Delegation to trigger the event on all children of form except textarea.

Let me know how this works.

Upvotes: 3

Jeff McCloud
Jeff McCloud

Reputation: 5927

It's not valid HTML, strictly speaking, but it works... You can put your div inside a <button type="submit"> and remove the button's default styling. Like the other answer that was given, the div must be inside the form for this work without additional JavScript. You'd also no longer need the tabindex on the div.

<form>
<input/>
<button type="submit">
<div>
</div>
</button>
</form>

and

button[type="submit"] {
  border: none;
  background: none;
  padding: 0;
  margin: 0;
  display: block;
}

https://jsfiddle.net/g2j2c0ra/2/

Upvotes: 1

Moses Davidowitz
Moses Davidowitz

Reputation: 982

Just give your form a name (eg id="test") and then use the following code to submit only the form with the given id:

$(function(){
 $("#test").keypress(function (e) {
    if (e.keyCode == 13) {
        alert('submitted');
        return false
    }
 });
});

Upvotes: 0

Related Questions