Jquery接受负值和非负值

时间:2013-02-07 12:50:22

标签: jquery

我试过这个。这只接受整数。我想要消极和非消极。

    $(function () {
        $('.spinner').keyup(function () {
            if (this.value.match(/[^0-9]/g)) {
                this.value = this.value.replace(/[^0-9]/g, '');
            }
        });
    });

3 个答案:

答案 0 :(得分:0)

尚未测试,但你尝试过这样的事情:

$(function () {
    $('.spinner').keyup(function () {
        if (this.value.match(/[^0-9-]/g)) {
            this.value = this.value.replace(/[^0-9-]/g, '');
        }
    });
});

在reg-ex中添加额外的' - ':第一个是指定范围,第二个是实际的char。

您还可以优化整个过程,并始终将值设置为:匹配的所有内容:

^[-]{0,1}[0-9]+

无线的开始或 - 接着是一系列数字,至少有一个或多个。

答案 1 :(得分:0)

不需要匹配和替换。而不是

if (this.value.match(/[^0-9]/g)) {
    this.value = this.value.replace(/[^0-9]/g, '');
}

使用

this.value = this.value.replace(/([+-]?\d+)/, '$1');

我假设您只希望在该字段中找到一个整数。

答案 2 :(得分:0)

您可以继续使用正则表达式,或者如果您更喜欢“纯逻辑”,这对我的眼睛来说更具可读性,您可以使用这样的代码:

$('.spinner').keyup(function (evt) {
    var previousValue = $(this).data("prev") || "";
    var currentValue = this.value;
    var valid = true;
    if (currentValue.length > 0 && currentValue !== "-") {
        //having something we can check:
        var number = Number(currentValue);

        //integer only if not NaN and integer value equals
        valid = (!isNaN(number) && parseInt(number, 10) == number);
    }

    if (valid) {
        $(this).data("prev", currentValue);
    } else {
        //restore last good value:
        this.value = (previousValue.length == 0) ? "" : parseInt(previousValue, 10);
    }
});

每次检查该值是否为有效整数且无效时,将恢复通过验证的先前值。

请注意Number()而不是parseInt()的使用,这是因为后者允许“5a”这样的内容被解析为5而Number("5a")会给出NaN值。

Live test case