按键事件后无法清除文本框

时间:2013-03-18 21:40:05

标签: javascript jquery

我知道这些问题到处都是,但这让我发疯了!!!

这是我的代码:

$(document).ready(function () {

        $('#MainContent_LoginUser_Password').keypress(function (e) {

            noCapsLock($('#MainContent_LoginUser_Password'), e, "Please turn off Caps Lock");
        });

    });
function noCapsLock(o, e, str) {
var s = String.fromCharCode(e.which);
if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
    alert(str);
    o.val('');

}     
}

我试图用给定的id清除文本框的值。上面的代码清除了文本,但是当按下新键时,会显示该键的值(大写字母)。 我已经尝试过change(),keyup(),keydown()函数,但它们似乎仍然没有清除输入的最后一个值的文本框。

任何帮助将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:1)

您只需添加event.preventDefault();

即可

您可能还希望将函数放在闭包中,使其不是全局的,并且您不需要在方法中再次重新找到html元素:

$(document).ready(function () {

    var noCapsLock = function(o, e, str) {
        var s = String.fromCharCode(e.which);
        if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
            alert(str);
            o.val('');
            e.preventDefault();
        }     
    }    

    $('#MainContent_LoginUser_Password').keypress(function (e) {
        noCapsLock($(this), e, "Please turn off Caps Lock");
    });
});

对于踢,我也把你的代码变成了一个jQuery插件,你可以很容易地应用到任何元素(它不会删除值只是停止按键):

(function($) {
    $.fn.noCapsLock = function(message) {
        this.keypress(function (e) {
            var char = String.fromCharCode(e.which);
            if (char.toUpperCase() === char && char.toLowerCase() !== char && !e.shiftKey) {
                window.alert(message);
                e.preventDefault();
            }         
        });
    };
})(jQuery);

像这样申请:

$(document).ready(function () {
    $('#MainContent_LoginUser_Password').noCapsLock('Please turn off Caps Lock!');
});

答案 1 :(得分:1)

您只需使用e.preventDefault();取消活动:

function noCapsLock(o, e, str) {
    var s = String.fromCharCode(e.which);
    if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
        e.preventDefault();
        alert(str);
        o.val('');
    }     
}

答案 2 :(得分:1)

我不会清除你案件中的文本框;如果用户以小写字母键入长文本,则点击CapsLock然后继续输入 - 整个输入将被删除。

对于该功能,您可以调用事件的preventDefault()方法或返回false(您可以read here on the differences between the methods):

    $(document).ready(function () {

        $('#MainContent_LoginUser_Password').keypress(function (e) {
           return noCapsLock(e, "Please turn off Caps Lock");
        });

    });
    function noCapsLock(e, str) {
        var s = String.fromCharCode(e.which);
        if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
            alert(str);
            return false;
        }
        return true;
    }
相关问题