Enter key event handling

asp.net, event-handling, html, jquery

Solution

You can do this:

jQuery('#MultiSearch2').on("keypress", function (e) {            

    if (e.keyCode == 13) {

        // Cancel the default action on keypress event
        e.preventDefault(); 

        search2();
    }
});

Problem

----- New Jquery for answer from comment ----- ``` function search2() { var urlString = 'Controls/LookUp.aspx?zipcode=' + $('#MultiSearch2').val(); window.location = urlString; return false; } jQuery('#MultiSearch2').bind("keypress", function (e) { if (e.keyCode == 13) { e.preventDefault(); search2(); } }); ``` Ok, here is how everything is kind of set up. I have a main.master page that has the following code in it. ``` <asp:Panel ID="PanelMainMaster" runat="server" DefaultButton="searchBTN"> <div id="HomeQuickSearch"> <input id="multiSearchStyle" type="text" placeholder ="search our store" /> <asp:Button OnClientClick="return searchZone()" runat="server" Text="Go" ID="searchBTN" /> </div> </asp:Panel> ``` I have another master page (tree) with the following code in it: ``` <asp:Panel ID="Panel2" runat="server" DefaultButton="submit"> <form name="ZipCodeForm" action="/Search.cfm" method="get"> <div style="margin-bottom: .25em">Search for a tree:</div> <input type="text" name="MultiSearch" id="MultiSearch" size="15" maxlength="50" style="margin-bottom: .25em"> <asp:Button Text="Search" runat="server" ID="submit" OnClientClick="return search()" /> </form> </asp:Panel> ``` And then, there is a custom content page created through a third party that shows up within the second master page with this code: ``` <div id="TreeStyle"> <Z:CustomMessage ID="Tree1" MessageKey="TreeHero" runat="server" /> </div> ``` The HTML rendered from the custom message: ``` <input id="MultiSearch2" type="text" name="MultiSearch2" maxlength="50"> <button id="submit2" name="submit2" type="submit">Search</button> ``` The page is rendered in following flow: - Main.Master - Tree.Master - Custom Message within Tree.Master The first two input textboxes handle the Enter button event click with the `DefaultButton` option on the `asp:Panel`. However, there is a third textbox and search button that is created because of the custom message within the `Tree.Master` and that CANNOT have any `ASP` in it, only `HTML`. My question is, how can I handle this Enter keypress event and have it search with the value from the third textbox instead of the value from the frist or second. I have tried this, but it didn't work. Not too much surprise there though. ``` function search2() { var urlString = 'Controls/LookUp.aspx?zipcode=' + $('#MultiSearch2').val(); window.location = urlString; return false; } jQuery('#MultiSearch2').on("keypress", function (e) { if (e.keyCode == 13) { search2(); } }); ``` I am also getting a jquery error I wasn't noticing before: `object [object Object] has no method 'on'`

Original source