如何使输入只接受两个小数,并且最多有10位数字

How to make an input to accept only two decimals and have maximum of 10 digits?

本文关键字:小数 数字 10位 两个 输入 何使      更新时间:2023-09-26

如何输入只接受两位小数,并且最多有10位数字?

我使用一个在onkeypress激活的函数,并获取插入到我的输入中的值的长度。我必须接受最多10位数字,最多2位小数,但在我输入这2位小数后,我无法引入任何其他数字。例如,如果我有1234.11,我就无法达到10234.11。

function onlyNumbers(){
if($('#GoalQuestionValue').val().toString().length>10) return false;
if($('#GoalQuestionValue').val().indexOf('.') != -1 && $('#GoalQuestionValue').val().toString().length-$('#GoalQuestionValue').val().indexOf('.') >2) return false;    
}
function onlyNumbers(){
var n = $('#GoalQuestionValue').val().toString().split('.');
if(n[0].length > 8 || n[0].length < 2) return false; else return true;
}

为什么不使用正则表达式来验证此需求:

if($('#GoalQuestionValue').val().toString().match(/[0-9]{8}'.[0-9]{2}/)!=null && $('#GoalQuestionValue').val().toString().length>11)

尝试keyup和keydown函数,而不是onclick或onchange。

我认为您必须在keypress侦听器中检查数字输入-

$("#GoalQuestionValue").keypress(function (e) {
    if (e.keyCode >= 48 && e.keyCode <= 57) {
        if (!isValidNumberStr(this.value)) return false;
    }
})

尝试使用事件"onchange"或"oninput"而不是"onclick"。如果你谈论的是算法,我认为这是最好的一个:

function onlyNumbers() {
    var myArray = $('#GoalQuestionValue').val().toString().match(/([0-9]*)'.?([0-9]*)?/);
    if(myArray[1]) {
        if(myArray[1].length > 10)
            return false;
        if(myArray[2]) {
            if( myArray[2].length > 2 )
                return false;
            if( myArray[1].length + myArray[2].length > 10)
                return false;
        }
        return true;
    }
    return false;
}