1

I have an issue where I'm trying to execute a search query from a textbox and attempting to use enter to initiate the search; however, it doesn't seem to be working. I'm wondering if vb.net/asp.net is doing a postback or something that I'm not aware of.

ASPX Page

 <form class="navbar-search">
     <input id="searchbox" type="text" class="search-query span3" placeholder="Search" />
     <div class="icon-search"></div>
 </form>

JQuery

$('#searchbox').keyup(function (e) {
    //alert("this will execute");
    if (e.which == 13) {
        alert("this will not execute");
        //window.location.href = "http://www.google.com/";
    }
});

I can't get the alert box to execute or the change location to work... if anyone can help I appreciate it.

7
  • Works here: jsfiddle.net/YAfeN -- Is your input actually an ASP.NET control? Commented May 1, 2013 at 13:57
  • 1
    It works only if you press enter key because of the condition e.which ==13 jsfiddle.net/M2GPb Commented May 1, 2013 at 13:58
  • 1
    you can't add a form into ASP.Net. ASP.Net add's a form be default for the __doPostback Commented May 1, 2013 at 14:00
  • Yes but when I press the enter key in my asp page the page refreshes instead of executing the code. I'm unsure why this is happening. Commented May 1, 2013 at 14:00
  • @Liam what do you mean you can't add a form into ASP.NET? His form doesn't have runat=server on it, and as long as it isn't nested in another form, he is OK. Although chances are he has put this form inside another one... Commented May 1, 2013 at 14:07

2 Answers 2

1

Try this:

$("#searchbox").keypress(function (e) {
    //alert("this will execute");
    var code = e.keyCode || e.which;
    if (code == 13) {
        alert("this will not execute");
        //window.location.href = "http://www.google.com/";
    }
});

and to stop page from refreshing on-enter use this:

$(document).keydown(function (e) {
    var code = e.keyCode || e.which;
    if (code === 13) {
        e.preventDefault();
    }
});

FIDDLE

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

1 Comment

Well this code is right, however I think OP has a different problem than he thinks..
0

Please try this.

$("#searchbox").live("keyup", function(event) {
        if (event.keyCode == 13) {
            //window.location.href = "http://www.google.com/";
        }
    });

This was worked for me...

4 Comments

I wouldn't be using live with the latest verion of jQuery.
i have use jquery-1.4.2.min.js version.
@tymeJV wouldn't be = can't! :)
@Mayur -- Unless a question is specifically asked in a lower version of jQuery, answering with one may not be beneficial, just a thought :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.