3

我有一个input类元素numbersOnly,它只允许(用键盘)写这个数字格式->#,##例如。2,04或者39,14

此外,当逗号前有 2 位数字时,第一个数字不允许为0

我正在使用此代码进行测试-但我仍然没有运气。

$('.numbersOnly').keyup(function () { 
    this.value = this.value.replace(/^[0-9]*[,][0-9]+$/,'');
});
4

2 回答 2

1

试试jQuery Masked Input 插件

于 2013-10-16T16:29:03.413 回答
0

可能是一种更简单的方法,但这似乎有效。jsfiddle:http: //jsfiddle.net/8GU6e/4/

这确实假设任何数量的数字都是有效的,我并不完全清楚你想要那个。“12,12345”有效吗?这假设它是。在 Chrome 和 Firefox 上测试。

$('.numbersOnly').keypress(function (e) { 
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;

    // Firefox will trigger this even on nonprintabel chars... allow them.
    switch (charCode) {
        case 8: // Backspace
        case 0: // Arrow keys, delete, etc
            return true;
        default:
    }

    var lastChar =  String.fromCharCode(charCode);

    // Reject anything not numbers or a comma
    if (!lastChar.match("[0-9]|,")) {return false;}

    // Reject comma if 1st character or if we already have one
    if (lastChar == "," && this.value.length == 0) {return false;}
    if (lastChar == "," && this.value.indexOf(",") != -1) {return false;}

    // Cut off first char if 0 and we have a comma somewhere
    if (this.value.indexOf(",") != -1 && this.value[0] == "0") {
        this.value = this.value.substr(1);
    }

    return true;
});
于 2013-10-16T16:28:26.090 回答