[英]How to make an input to accept only two decimals and have maximum of 10 digits?
How to make an input to accept only two decimals and have maximum of 10 digits? 如何使输入仅接受两个小数并最多包含10个数字?
I use a function that is activated at onkeypress
and gets the length of the value inserted in my input. 我使用在onkeypress
上激活的函数,该函数获取输入中插入的值的长度。 I got to make it to accept max 10 digits, and maximum of 2 decimals, but after I put those 2 decimals, I can't introduce any other number. 我必须使它最多接受10个数字,最多接受2个小数,但是在输入这2个小数后,我不能再引入其他任何数字了。 For example if I have 1234.11, I can't make it to 10234.11. 例如,如果我有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;
}
Instead of "onclick" try to use events "onchange" or "oninput". 尝试使用事件“ onchange”或“ oninput”代替“ onclick”。 If you are talking about algorithm, I think this is the best one: 如果您正在谈论算法,我认为这是最好的一种:
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;
}
为什么不使用正则表达式来验证此要求:
if($('#GoalQuestionValue').val().toString().match(/[0-9]{8}\\.[0-9]{2}/)!=null && $('#GoalQuestionValue').val().toString().length>11)
尝试使用keyup和keydown功能,而不要使用onclick或onchange。
I think you have to check in keypress
listener for digit input - 我认为您必须在keypress
监听器中签入数字输入-
$("#GoalQuestionValue").keypress(function (e) {
if (e.keyCode >= 48 && e.keyCode <= 57) {
if (!isValidNumberStr(this.value)) return false;
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.