Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pressing Enter Always Submits Form

I have a simple text box and button type input on my page.

 <input id="sText" type="text" />
 <input id="sButton" type="button" value="button" />

I capture a button click using jQuery.

  $("[id$=sButton]").click(function () {

      ...do Stuff  

  });

The above code works just fine as long as I manually click the button. I started running into problems when I wanted to use the "enter" key to click the button. No matter what I do, I cannot prevent the enter key from performing it's default submit function.

The first thing I did was change the input type from "submit" to "button".

I tried setting the form's onsubmit to onsubmit="return false;"

I tried using jQuery to capture the enter key event:

 $("#sText").keyup(function (event) {
        if (event.keyCode == 13) {
            alert("Enter!");
            // $("#sButton").click();
        }
    });

Every time I press the enter key, it's like I'm submitting the form, the whole page refreshes. The above jQuery code does capture the "enter" keystroke, but the form still submits and refreshes the page.

I'm not sure whats going on.

like image 846
SharpBarb Avatar asked Jan 05 '12 21:01

SharpBarb


1 Answers

You need to cancel the action.

event.preventDefault();

BUT I believe you can only kill the form submission with keydown, not keyup.

like image 133
epascarello Avatar answered Sep 28 '22 09:09

epascarello