Isaac Levin
Isaac Levin

Reputation: 2899

Stop Enter key from firing button click event

I am hoping this is easy, but I have looked and can't find a solution that will work for me. I have an aspx page with 2 user controls on it. One is a user control with a spun-up Auto Complete text box, that I want the "Enter" key to to cause a postback.

I have a button in the other control on the page that the onClick does something else. When I put text in the Auto Complete and press enter, the onClick for the button fires. Is there a way to have the enter key not cause the onClick to fire.

I have tried some javascript to disable the enter key press, but that breaks my text box enter.

What are my options.

EDIT 1

Here is some markup that I have

<uc:CompanyAC runat="server" ID="ac" />
<cc2:GenericGridView OnHtmlDataCellPrepared="HtmlDataCellPrepared"
KeyFieldName="CompanyID" ID="gridCompanies" DataSourceID="ManageCompaniesObjectDataSource" runat="server" 
AutoGenerateColumns="False" />

The CompanyAC control has a textbox with some jquery that does autocomplete WS call (no need to show that

<asp:TextBox ID="searchbox" runat="server" Width="400px" />

The GenericGridView control contains a button

<asp:Button runat="server" ID="Button" Text="New" AllowFocus="false" OnClick="Button_Click" />

So what happens is that when the Enter Key is hit when the focus is on the Textbox, the button that is in the other control fires its onclick. I do not want that to happen, but I still want the postback to happen

Upvotes: 3

Views: 6208

Answers (2)

prothid
prothid

Reputation: 606

If you're using jQuery, you might try this:

$('input').on('keypress', function(e){
    // Attempt form submit (after event function exits).
    var f = $(this).parents('form');
    setTimeout(function(){f.submit();}, 1);

    // Return false to prevent form submit when enter key is pressed.
    return !((window.event) ? window.event.keyCode : e.which)==13);
});

Upvotes: 0

Falguni Panchal
Falguni Panchal

Reputation: 8981

try this

$('input').keypress(function(event){
        if(event.keyCode==13)
        {
            event.preventDefault();

            }
        })

Upvotes: 1

Related Questions