Mehmet Ince Mehmet Ince - 5 months ago 24x
Javascript Question

Prevent default doesnt work when enter key pressed

my control looks like this;

<asp:Button ID="btnLogOut" runat="server" Text="Exit" ClientIDMode="Static" OnClick="btnLogOut_Click" />

and js event;

$("#btnLogOut").keyup(function (event) {
if (event.which == 13 || event.keyCode == 13) {
return false;
else return true;

On the page, when I pressed enter key, it triggers btnLogOut button. To prevent this,
I wrote above js event. alert says that keyCode is 13 but it's not preventing click function and I log out.

How Can I fix this? This especially occurs in IE

not working also.


preventDefault() is a method of the Event object (event) so you need to call it on that: event.preventDefault().

However, in the keyup event the key has already been handled so there is no point in blocking the event. Do it in keydown instead.