我在讓用戶在具有相同類的文本框中輸入數字值時出現問題。防止用戶在小數點前2位後輸入更多數字
我想:
- 允許用戶小數點前只輸入2個數字和另外2之後;否則所有按鍵都記錄除箭頭鍵,退格鍵和刪除鍵
本期
- 用戶只能進入2號;然而,在他/她添加小數點後,他們可以在其之前添加更多數字。
- 目前,用戶只能輸入5位數 - 小數點前2位,小數點後2位。當他們在小數點後刪除一位數字時,他們仍然可以在該小數點之前向數字添加更多數字。
我的HTML:
<form method="post">
<div class="row">
<label>Val 1</label>
<input type="text" class="validate" name="val1" maxlength="5" />
</div>
<div class="row">
<label>Val 2</label>
<input type="text" class="validate" name="val2" maxlength="5" />
</div>
<div class="row">
<label>Val 3</label>
<input type="text" class="validate" name="val3" maxlength="5" />
</div>
<div class="row">
<button type="submit">Send</button>
</div>
</form>
我的JS:
Number.prototype.between = function (a, b, inclusive) {
var min = Math.min.apply(Math, [a,b]),
max = Math.max.apply(Math, [a,b]);
return inclusive ? this >= min && this <= max : this > min && this < max;
};
$('.validate').keypress(function(event) {
var v = parseFloat($(this).val() + String.fromCharCode(event.which));
textValue = parseFloat(v).toString();
var newVal = parseInt(textValue.substr(0, textValue.indexOf(".")));
console.log(newVal);
if(textValue.length < 6){
if(!parseFloat(v).between(0,99.99,true)) {
v = this.value.substring(0, 2);
$(this).val(v);
return false;
}
return true;
}
});
這裏是鏈接到我的fiddel DEMO
我剛剛發現這種方法的問題。當用戶複製/粘貼具有2個以上小數點的數字時,它是允許的。所以我使用了BGS&Aashray提出的兩種方法。 – Sung