Ce Nedra
Ce Nedra

Reputation: 45

How to stop a jQuery function being run on keydown when Tab key is pressed

I am new to jQuery and haven't been able to find a solution to this.

I have this HTML:

<input type="text" id="Box1" /><br />
<input type="text" id="Box2" />

And jQuery:

$("#Box1").keydown(function () {
    $("#Box2").val("");
});
$("#Box2").keydown(function () {
    $("#Box1").val("");
});

Example here: http://jsfiddle.net/tv4my/

When you type in "Box1" then start typing in "Box2", Box1's content is cleared. This is good, however I don't want this function to run if the Tab key is pressed, i.e. I don't want Box1 to be cleared if I press the Tab key inside Box2. How do I write this in jQuery?

Upvotes: 1

Views: 1181

Answers (2)

Ranganadh Paramkusam
Ranganadh Paramkusam

Reputation: 4358

Use e.preventDefault() when clicking on that key:

$("input").keydown(function(e){
    if(e.keyCode == "9"){
        e.preventDefault();
    }
});

Check the JSFiddle here.

Upvotes: 1

patrickmcgraw
patrickmcgraw

Reputation: 2495

You need to check the key used to initiate the event:

$("#Box1").keydown(function (e) {
    // If the pressed key is not tab (9) then reset Box2
    if(e.keyCode !== 9){
        $("#Box2").val("");
    }
});
$("#Box2").keydown(function (e) {
    // If the pressed key is not tab (9) then reset Box1
    if(e.keyCode !== 9){
        $("#Box1").val("");
    }
});

Upvotes: 1

Related Questions