在textbox jQuery上验证keypress上的用户输入

Sou*_*rav 3 jquery jquery-validate

如何在jQuery中编码,这样用户就无法按下"." 键入文本框?

我可以用这样的javascript编码,在每个按键上浏览器检查是否按下了一个键,如果它是点然后是子串(0,len-1),但它闪烁!我想完全阻止按键!

kar*_*m79 5

这应该工作.它没有经过跨浏览器测试:

$("#theTextBox").keyup(function() {
    if($(this).val().indexOf('.') !== -1) {
        var newVal = $(this).val().replace('.', '');
        $(this).val(newVal);
    }
});
Run Code Online (Sandbox Code Playgroud)

你可以在这里试试.

编辑:我认为这更好:

function doItPlease() {
    if ($(this).val().indexOf('.') !== -1) {
        var newVal = $(this).val().replace('.', '');
        $(this).val(newVal);
    }
}

$("#theTextBox").bind("keydown keyup", doItPlease);
Run Code Online (Sandbox Code Playgroud)

在这里尝试不那么糟糕的解决方案.

编辑(再次):我赞成上述解决方案,因为我非常喜欢反馈方面.那就是说,我认为这就是你所追求的:

$("#theTextBox").keyup(function(e) {
    if (e.which != 190) {
        return true;
    }
    e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

在这里试试吧.