Pressing Enter always submits a form

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

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

I will write a button using jQuery.

  $("[id$=sButton]").click(function () { ...do Stuff }); 

The code above works just fine, while I manually push the button. I had problems when I wanted to use the enter key to press a button. No matter what I do, I cannot prevent the enter key from executing the default send function.

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

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

I tried using jQuery to capture an input event:

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

Every time I press the enter key, I like to submit the form, the whole page is updated. The above jQuery code captures the "enter" key, but the form still submits and refreshes the page.

I'm not sure what is going on.

+6
source share
2 answers

You need to undo the action.

 event.preventDefault(); 

BUT I believe that you can only kill a form submission using keydown, not keyup.

+9
source

Epascarello is right, you need to cancel sending with the code that he gave you. But you also need to change the button back to the send type so that the ENTER key and button press do the same. Thus, you only need to handle the cancellation of sending in one area.

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

JQuery

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

Thus, one function processes the ENTER key and button.

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

+1
source

Source: https://habr.com/ru/post/905251/


All Articles