修改onkeyup事件以忽略Tab键

时间:2013-10-19 05:36:48

标签: javascript jquery

$(document).ready(function() {
$("#textboxA").keyup(function () {
var message;
message ="Currently Textbox A in use";
$("#error").slideDown("fast");
document.getElementById('error').innerHTML=message;

});

$("#textboxB").keyup(function () {
var message;
message ="Currently Textbox B in use";
$("#error").slideDown("fast");
document.getElementById('error').innerHTML=message;

});    

});

在上面的代码中,每当我按Tab键从textboxA移动到textboxB时,jquery函数就会触发并显示消息。如何防止?

Fiddle setup here

2 个答案:

答案 0 :(得分:2)

检查以确保未按下标签键。

$(document).ready(function() {
    $("#textboxA").keyup(function (e) {
        if(e.keyCode != 9){
             var message;
             message ="Currently Textbox A in use";
             $("#error").slideDown("fast");
             document.getElementById('error').innerHTML=message;

             });

       $("#textboxB").keyup(function (e) {
             if(e.keyCode != 9){
             var message;
             message ="Currently Textbox B in use";
             $("#error").slideDown("fast");
             document.getElementById('error').innerHTML=message;

             });  
             }

       }
});

答案 1 :(得分:1)

简单检查选项卡keyCode。如果不是tab键,则执行。这是代码

$(document).ready(function () {
    $("#textboxA").keyup(function (e) {
        var message;
        message = "Currently Textbox A in use";
        if (e.keyCode != 9) {
            $("#error").slideDown("fast");
            document.getElementById('error').innerHTML = message;
        }
    });

    $("#textboxB").keyup(function (e) {
        var message;
        message = "Currently Textbox B in use";
        if (e.keyCode != 9) {
            $("#error").slideDown("fast");
            document.getElementById('error').innerHTML = message;
        }
    });

});

以下是demo