10

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.

Mister Epic
  • 16,295
  • 13
  • 76
  • 147
Karthi Keyan
  • 4,243
  • 5
  • 24
  • 47

1 Answers1

12

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;
    }
  });
Mister Epic
  • 16,295
  • 13
  • 76
  • 147
  • is it necessarry to use event.preventDefault() ? – fubo Nov 24 '14 at 07:47
  • @fubo Yes, as the default behaviour would be to initiate a postback. You need to prevent this. – Mister Epic Nov 24 '14 at 13:55
  • ok - in my case the return false prevents a postback. anyway good solution +1 – fubo Nov 24 '14 at 14:44
  • You also need to select other input elements, like radio and checkboxes, as the form will submit if those elements are selected and the user then hits the enter button. $('input[type="text"], input[type="radio"], input[type="checkbox"]').keydown... – Dan Oct 04 '16 at 19:20