Mehmet Ince
Mehmet Ince

Reputation: 4179

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.

Upvotes: 5

Views: 12134

Answers (6)

Adil
Adil

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

Fezzy
Fezzy

Reputation: 64

Try changing $("#btnLogOut").preventDefault(); to event.preventDefault();

Upvotes: 1

ThiefMaster
ThiefMaster

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

PSL
PSL

Reputation: 123739

Yo need to use event.preventDefault()

Upvotes: 1

Halcyon
Halcyon

Reputation: 57729

You can't cancel in the keyup fase, you can in keydown.

And use event.preventDefault();

Upvotes: 4

Rob
Rob

Reputation: 4947

You should use event.preventDefault(); instead of calling preventDefault() on the object itself.

Upvotes: 2

Related Questions