Mehmet Ince Mehmet Ince - 7 months ago 41
Javascript Question

Prevent default doesnt work when enter key pressed

my asp.net 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) {
alert(event.keyCode);
$("#btnLogOut").preventDefault();
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

Edit:
event.preventDefault
not working also.

Answer

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.