Reputation: 4179
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.
Upvotes: 5
Views: 12134
Reputation: 148120
The preventDefault is used with event object
$("#btnLogOut").keyup(function (event) {
if (event.which === 13 || event.keyCode === 13) {
alert(event.keyCode);
event.preventDefault();
return false;
}
else return true;
});
Upvotes: 3
Reputation: 64
Try changing $("#btnLogOut").preventDefault();
to event.preventDefault();
Upvotes: 1
Reputation: 318518
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.
Upvotes: 12
Reputation: 57729
You can't cancel in the keyup
fase, you can in keydown
.
And use event.preventDefault();
Upvotes: 4
Reputation: 4947
You should use event.preventDefault();
instead of calling preventDefault()
on the object itself.
Upvotes: 2