asp.net.netenterdefaultbutton

ASP .NET - Submit on Enter - Prevent 'defaultbutton' when other button has focus


I have a search form consisting of the following...

<asp:Panel DefaultButton="btnSearch" ... >

    [...search criteria fields...]

    <asp:Button ID="btnReset" OnClick="btnReset_Click" ... />
    <asp:Button ID="btnSearch" OnClick="btnSearch_Click" ... />

</asp:Panel>

The desired behaviour is that pressing the Enter key should invoke btnSearch_Click (which is working thanks to the DefaultButton attribute in the asp:panel)

The problem is that when btnReset has focus, pressing Enter should invoke btnReset_Click instead (which it doesn't - it's always btnSearch).

Is this easily achievable somehow, or am I going to have to hack up some bespoke JS to intercept .NET's defaultButton event handler?

Thanks in advance.


ETA: Here's a reusable solution I went with based on HenryChuang's accepted answer below.

  1. Add a custom attribute preventDefaultButton to panels.

    <asp:Panel DefaultButton="btnSearch" preventDefaultButton="btnReset" >
    
        [...search criteria fields...]
    
        <asp:Button ID="btnReset" OnClick="btnReset_Click" ... />        
        <asp:Button ID="btnSearch" OnClick="btnSearch_Click" ... />
    
    </asp:Panel>
    
  2. Run the following jQuery on pageload.

    $("div[preventDefaultButton]").each(function () {
    
        var div = $(this);
        var keypressEvent = div.attr("onkeypress");
        var btn = $("input[id$=" + div.attr("preventDefaultButton") + "]");
    
        btn.on("focus", { div: div }, function (event) {
            event.data.div.attr("onkeypress", "");
        });
    
        btn.on("blur", { div: div, keypressEvent: keypressEvent }, function (event) {
            event.data.div.attr("onkeypress", event.data.keypressEvent);
        });
    
    });
    

Solution

  • see the panel generate html

    <div id="yourPanelClientID" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'btnSearch')">
    

    so, when btnReset onfocus we break onkeypress event of Panel, add below to btnReset, remember when btnReset onblur, change Panel keypress to oringinal

    onfocus="document.getElementById('yourPanelClientID').onkeypress = '';"
    onblur="funA();"
    function funA() {
            document.getElementById('yourPanelClientID').onkeypress = function () { return WebForm_FireDefaultButton(event, "btnSearch") };
        }
    

    like this

     <asp:Button ID="btnReset"
     onfocus="document.getElementById('yourPanelClientID').onkeypress = '';" 
    onblur="funA();"
    onclick="btnReset_Click" .../>