【问题标题】:jQuery script to validate number on enteringjQuery脚本在输入时验证数字
【发布时间】:2012-04-10 17:45:04
【问题描述】:

我想知道是否有可能使用 jQuery 执行以下任务:防止用户输入大于 10 或小于 0 的数字。

例如,9.10 这样的数字是可以的,但 81、10.01、11 或负数是错误的值。

为了更好地了解情况,验证是为了在测试后输入成绩。

谢谢。

【问题讨论】:

  • 当然可以。你试过什么?您希望何时进行检查?模糊?提交时?

标签: jquery numeric


【解决方案1】:

此代码仅允许您在框中输入数字,不会接受任何会使数字小于 0 且大于 10 的输入。

var $grade = $('#grade');

$grade.keydown( function (e) {
    var code = e.which,
        chr = String.fromCharCode(code), // key pressed converted to s string
        cur = $grade.val(),
        newVal = parseFloat(cur + chr); // what the input box will contain after this key press

    // Only allow numbers, periods, backspace, tabs and the enter key
    if (code !== 190 && code !== 8 && code !== 9 && code !== 13  && !/[0-9]/.test(chr)) {
        return false;
    }

    // If this keypress would make the number
    // out of bounds, ignore it
    if (newVal < 0 || newVal > 10) {
        return false;
    }

});

http://jsfiddle.net/WPdVq/

【讨论】:

    【解决方案2】:

    如果您想在他们退出输入字段时显示某些内容,您可以使用change event

    $('.target').change(function() {
        if($(this).val() > 10) {
            // Do something, like warn them and/or reset to empty text.
            alert('Greater than 10.');
            $(this).val('');
        }       
    });         
    

    jsfiddle working example

    或者,如果您想在每次击键后显示一些内容,您可以使用keyup 事件。

    【讨论】:

    • 看起来不错,谢谢。是否可以对其进行更新,使其只接受数值和点?
    • 查看无用代码的answer。他有一个更完整的答案,包括你的要求。
    【解决方案3】:

    我建议这个库: jquery-numeric

    插件的主页在这里: http://code.webmonkey.uk.com/plugins/

    有demo和使用可以查看源码看看使用:

    http://code.webmonkey.uk.com/plugins/jquery.numeric/test.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多