How to prevent postback while pressing enter key from inside html input textbox?

Karthi Keyan picture Karthi Keyan · Feb 5, 2014 · Viewed 11.5k times · Source

Am using html input textbox in .aspx page, when i change values in that textbox and hit enter key means page get postback. How to prevent this postback other than returning false in "onkeypress" event.

Code:

textBox[0].setAttribute("onkeydown", "return (event.keyCode!=13);");

Thanks,
Karthik.

Answer

Mister Epic picture Mister Epic · Feb 5, 2014

You need to use javascript to prevent the default behaviour of clicking enter, which is to submit the form. You need to do something like this (and I'm using jQuery here, which is included by default with an ASP.Net app):

$('input[type="text"]').keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });