6

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.

2 Answers 2

9

You need to cancel the action.

event.preventDefault(); 

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

Sign up to request clarification or add additional context in comments.

2 Comments

In addition to adding "event.preventDefault()" I also had to change "keyup" to "keypress", Neither keyup or keydown worked. Thanks!
Seems like keeping the enter key check and the button as a button type instead of switching it back to a submit is using a lot of extra code.
1

Epascarello is right, you need to cancel the for submit with the code he gave you. But you should also change the button back to a submit type so that the ENTER key and Clicking the button do the same thing. That way you only have to handle the cancellation of the submit in one area.

<input id="sButton" type="submit" value="Submit" /> 

JQuery:

$("#YourFormId").submit(function(event){ event.preventDefault(); ...do Stuff }); 

This way one function handles the ENTER key and the button click.

EDIT: Put the event.preventDefault() as the first statement.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.