Question

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);
        });
    
    });
    
Was it helpful?

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" .../>

OTHER TIPS

you need to change DefaultButton attribute of your panel but this will work for only one at a time, better way would be to have Javascript to capture enter event and process accordingly.

One way can be having multiple panels, have a look at http://www.jstawski.com/archive/2008/09/23/multiple-default-buttons.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top