[英]restrict the “textfield” to accept only digits and maximum 10 digits in magento form
[英]How to make an input to accept only two decimals and have maximum of 10 digits?
如何使輸入僅接受兩個小數並最多包含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;
}
嘗試使用事件“ 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;
}
為什么不使用正則表達式來驗證此要求:
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;
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.