Reputation: 3165
How to make an input to accept only two decimals and have maximum of 10 digits?
I use a function that is activated at onkeypress
and gets the length of the value inserted in my input. 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. For example if I have 1234.11, I can't make it to 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;
}
Upvotes: 0
Views: 1521
Reputation: 736
Instead of "onclick" try to use events "onchange" or "oninput". 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;
}
Upvotes: 0
Reputation: 3170
I think you have to check in keypress
listener for digit input -
$("#GoalQuestionValue").keypress(function (e) {
if (e.keyCode >= 48 && e.keyCode <= 57) {
if (!isValidNumberStr(this.value)) return false;
}
})
Upvotes: 0
Reputation: 1191
function onlyNumbers(){
var n = $('#GoalQuestionValue').val().toString().split('.');
if(n[0].length > 8 || n[0].length < 2) return false; else return true;
}
Upvotes: 1
Reputation: 1088
try keyup and keydown functions instead of onclick or onchange.
Upvotes: 0
Reputation: 2763
Why not use a regex to validate this requirement:
if($('#GoalQuestionValue').val().toString().match(/[0-9]{8}\.[0-9]{2}/)!=null && $('#GoalQuestionValue').val().toString().length>11)
Upvotes: 0