Search code examples
jqueryfunctionpostbackkeyup

JQuery allow function call but prevent postback with enter key


In an ASP.Net application, I have a textbox control on a web form that a user can enter some filter criteria into and a button next to it that, when clicked, will perform a search using an Ajax call which will in turn populate another control.

I would like to make it so that if the text box has focus, and the user hits the return/enter key, the search is performed in the same manner as if the search button was clicked. Currently the whole form gets posted back.

I am using the jquery below to prevent the postback, but if I include the second block, it never gets hit...

$(window).keyup(function (event)
{
    if (event.keyCode == 13)
    {
        event.preventDefault();
        return false;
    }
});

$("#SearchTextBox").keyup(function (event)
{
    if (event.keyCode == 13)
    {
        $.DoFilterSearch();
    }
});

I'm assuming this has something to do with the DOM hierarchy, but don't know enough about it to be sure.

Essentially, I'd like to know how I allow the enter button to be pressed for a given control, and if it's pressed anywhere else, to be ignored (in terms of postbacks)


Solution

  • This code worked for me:

    $('#SearchTextBox').keydown(function(event){ // or keypress
      if(event.keyCode == 13) {
         event.preventDefault();
         return false;
      }
    });