208

I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:

$('form').keypress( function( e ) {
  var code = e.keyCode || e.which;

  if( code === 13 ) {
    e.preventDefault();
    return false; 
  }
})

As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.

Does anyone know of a more sophisticated technique for doing this?

Similarly, are there any pitfalls to this solution that I'm just not aware of?

Thanks.

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Rob Wilkerson
  • 40,476
  • 42
  • 137
  • 192
  • 1
    This can happen when using angular reactive forms as well, not only useful for JQuery, but for angular development as well. – HDJEMAI Nov 24 '18 at 22:22

12 Answers12

454

Using

<button type="button">Whatever</button>

should do the trick.

The reason is because a button inside a form has its type implicitly set to submit. As zzzzBoz says, the Spec says that the first button or input with type="submit" is what is triggered in this situation. If you specifically set type="button", then it's removed from consideration by the browser.

76484
  • 8,498
  • 3
  • 19
  • 30
Maddog
  • 4,746
  • 4
  • 14
  • 11
  • 1
    sweet, thanks, seems like buttons in IE8 for me capturing clicks, `type="button"` seems to resolve this... Thanks! p.s. any idea as to why this is? ie8 treating buttons as type submit? Weird. – Quang Van Oct 29 '12 at 08:44
  • 3
    Good answer, this hints to the browser which buttons aren't submit buttons, so it can do the right thing without reordering the markup. – Don Spaulding Feb 20 '13 at 16:07
  • 2
    @Leinster's answer covers the reason for this quirk - "A button with no type attribute is treated the same as a button with its type set to submit." – Bucket Jan 24 '14 at 18:09
  • 2
    Same applies for `` (will trigger click) and `` (will not trigger click) – Marius Balčytis Apr 10 '14 at 13:10
  • I had the same problem with I need the image so this solution didn't work. My only option seems to be event.preventDefault(); – johannes Mar 31 '19 at 09:30
  • Damn man! I went down into Angular rabbit hole, and the answer was so simple! – SimonRabbit Nov 06 '20 at 10:01
  • amazing, thanks it's solve my problem, it seems I know the cause, when press enter is considered to be submitting the form, so the button without type is triggered – yussan Jan 24 '22 at 04:10
64

It is important to read the HTML specifications to truly understand what behavior is to be expected:

The HTML5 spec explicitly states what happens in implicit submissions:

A form element's default button is the first submit button in tree order whose form owner is that form element.

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

This was not made explicit in the HTML4 spec, however browsers have already been implementing what is described in the HTML5 spec (which is why it's included explicitly).

Edit to add:

The simplest answer I can think of is to put your submit button as the first [type="submit"] item in the form, add padding to the bottom of the form with css, and absolutely position the submit button at the bottom where you'd like it.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • 2
    There I was cursing IE, turns out it was my sloppy markup all along! Cheers! – Shawson Jul 02 '13 at 13:57
  • 2
    Wow... Thank you good sir. This was an accidental find. I couldn't even fathom why a click event was being fired from hitting the enter key, but your quote led me to http://www.w3.org/TR/html5/forms.html#implicit-submission – chemoish Nov 21 '14 at 05:55
  • The link is broken. I think https://w3c.github.io/html/sec-forms.html#implicit-submission is the new url. – T. Junghans Oct 20 '16 at 11:50
35

Where ever you use a <button> element by default it considers that button type="submit" so if you define the button type="button" then it won't consider that <button> as submit button.

Ram Thota
  • 539
  • 5
  • 9
22

I don't think you need javascript or CSS to fix this.

According to the html 5 spec for buttons a button with no type attribute is treated the same as a button with its type set to "submit", i.e. as a button for submitting its containing form. Setting the button's type to "button" should prevent the behaviour you're seeing.

I'm not sure about browser support for this, but the same behaviour was specified in the html 4.01 spec for buttons so I expect it's pretty good.

Leinster
  • 401
  • 3
  • 5
16

By pressing 'Enter' on focused <input type="text"> you trigger 'click' event on the first positioned element: <button> or <input type="submit">. If you press 'Enter' in <textarea>, you just make a new text line.

See the example here.

Your code prevents to make a new text line in <textarea>, so you have to catch key press only for <input type="text">.

But why do you need to press Enter in text field? If you want to submit form by pressing 'Enter', but the <button> must stay the first in the layout, just play with the markup: put the <input type="submit"> code before the <button> and use CSS to save the layout you need.

Catching 'Enter' and saving markup:

$('input[type="text"]').keypress(function (e) {
    var code = e.keyCode || e.which;
    if (code === 13) {
        e.preventDefault();
        // also submit by pressing Enter:
        $("form").submit();
    }
});
fatal_error
  • 5,457
  • 2
  • 18
  • 18
Feniks502
  • 229
  • 1
  • 2
  • 6
  • 1
    Shouldn't the if statement have a brace to execute both statements only when enter is pressed? Otherwise the submit will happen for every key press. Reminds me of goto fail. :) – danmiser May 17 '14 at 02:07
  • @danmiser you're correct, so it should be fixed now. – fatal_error Apr 27 '22 at 20:14
2

Pressing enter in a form's text field will, by default, submit the form. If you don't want it to work that way you have to capture the enter key press and consume it like you've done. There is no way around this. It will work this way even if there is no button present in the form.

Sparafusile
  • 4,696
  • 7
  • 34
  • 57
  • 4
    I don't think the issue is that the form submits, it is that it triggers the `click` action on the button elements wish is an unintended consequence – Martin Jespersen Jan 21 '11 at 21:33
  • You are correct. Either way, the result is the same - you have to capture the enter key to prevent unwanted form submits. – Sparafusile Jan 21 '11 at 23:05
2

You can use javascript to block form submission until the appropriate time. A very crude example:

<form onsubmit='return false;' id='frmNoEnterSubmit' action="index.html">

    <input type='text' name='txtTest' />

    <input type='button' value='Submit' 
        onclick='document.forms["frmNoEnterSubmit"].onsubmit=""; document.forms["frmNoEnterSubmit"].submit();' />

</form>

Pressing enter will still trigger the form to submit, but the javascript will keep it from actually submitting, until you actually press the button.

Dave
  • 4,375
  • 3
  • 24
  • 30
2

Dom example

  <button onclick="anotherFoo()"> Add new row</button>
  <input type="text" name="xxx" onclick="foo(event)">

javascript

function foo(event){
   if(event.which == 13 || event.keyCode == 13) // for crossbrowser
   {
     event.preventDefault(); // this code prevents other buttons triggers use this
     // do stuff
   }
}

function anotherFoo(){
  // stuffs.
}

if you don't use preventDefault(), other buttons will triggered.

0

I would do it like the following: In the handler for the onclick event of the button (not submit) check the event object's keycode. If it is "enter" I would return false.

Satyajit
  • 3,839
  • 1
  • 19
  • 14
  • That keycode is always being passed as though it were a click. Therein lies the problem. :-) – Rob Wilkerson Jan 21 '11 at 21:10
  • Then I guess you do it the hard way - handle the onkeydown event on the button as well. The handler will be passed a keyEvent; check the keyCode -> if 13, preventDefault. This way you can actually let users press enter on that button as well without the side effect of executing the click event. – Satyajit Jan 21 '11 at 22:14
0

My situation has two Submit buttons within the form element: Update and Delete. The Delete button deletes an image and the Update button updates the database with the text fields in the form.

Because the Delete button was first in the form, it was the default button on Enter key. Not what I wanted. The user would expect to be able to hit Enter after changing some text fields.

I found my answer to setting the default button here:

<form action="/action_page.php" method="get" id="form1">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
</form>
<button type="submit" form="form1" value="Submit">Submit</button>

Without using any script, I defined the form that each button belongs to using the <button> form="bla" attribute. I set the Delete button to a form that doesn't exist and set the Update button I wanted to trigger on the Enter key to the form that the user would be in when entering text.

This is the only thing that has worked for me so far.

Lece
  • 2,339
  • 1
  • 17
  • 21
  • 1
    Please check [how to answer on stackoverflow](https://stackoverflow.com/help/answering) – Morse Apr 25 '18 at 02:34
0

You can do something like this.

bind your event into a common function and call the event either with keypress or button click.

for example.

function callME(event){
    alert('Hi');
}



$('button').on("click",callME); 
$('input ').keypress(function(event){
  if (event.which == 13) {
    callME(event);
  }
});
newbdeveloper
  • 394
  • 3
  • 11
-1

I added a button of type "submit" as first element of the form and made it invisible (width:0;height:0;padding:0;margin:0;border-style:none;font-size:0;). Works like a refresh of the site, i.e. I don't do anything when the button is pressed except that the site is loaded again. For me works fine...

Gynteniuxas
  • 7,035
  • 18
  • 38
  • 54
torabe
  • 1