ASP.Net page enter key causing post back

I have an aspx page that postsback when it should not. there are two text boxes, two listboxes and two buttons on the page. if at any-point the enter key is pressed the first button is given focus and “clicked” resulting in a loss of selection within the listboxes.

How do I disable this? There are tons of tutorials on how to capture the enter button and execute a method but I could not find one on how to simply disable the neat “let me grab the first button I find and click it” feature mentioned above.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

  • You could set the DefaultButton on the Form or a Panel. This way you have full control what happens.
  • Set UseSubmitBehavior=”False” on your Buttons. This disables the “AutoPostback” on Enter.

I would prefer the second if i wanted to prevent Postbacks on Enter completely.

Method 2

are you using jQuery?

if so:

$(document).keypress(function(e)
{
    if(e.keyCode === 13)
    {
        e.preventDefault();
        return false;
    }
});

Method 3

Use the below code to disable enter key causing postback. This piece of code will block the enter key in all browsers 4.0 above, except when enter is pressed in a Textarea or on the Submit button itself.

<script language="JavaScript">
var nav = window.Event ? true : false;
if (nav) {
window.captureEvents(Event.KEYDOWN);
window.onkeydown = NetscapeEventHandler_KeyDown;
} else {
document.onkeydown = MicrosoftEventHandler_KeyDown;
}

function NetscapeEventHandler_KeyDown(e) {
if (e.which == 13 && e.target.type != 'textarea' && e.target.type != 'submit') { 
return false; 
}
return true;
}

function MicrosoftEventHandler_KeyDown() {
if (event.keyCode == 13 && event.srcElement.type != 'textarea' && 
event.srcElement.type!= 'submit')
return false;
return true;
}
</script>

Method 4

Only put this on you ASP.Net TextBox control:

<asp:TextBox ID="TextBox1" runat="server"
   onkeydown = "return (event.keyCode!=13);" >
</asp:TextBox>

Method 5

This is default behavior of a web application, you could take one of the tutorials that you found and hide that behavior, by simply abandoning the submit.

Method 6

<body onkeydown = "return (event.keyCode!=13)">


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x