[英]Preventing user to enter more numbers after 2 digits before decimal point
I'm having a problem with letting users enter numeric values in my textboxes which have the same class. 我在让用户在具有相同类的文本框中输入数字值时遇到问题。
What I Want: 我想要的是:
Current Issue 目前的问题
My HTML: 我的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>
My JS: 我的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;
}
});
Here is the link to my fiddel DEMO 这是我的烦恼示范的链接
Try this : 尝试这个 :
<input type="text" class="validate" name="val1" maxlength="5" onkeypress="return CheckDecimalValues(event)" />
function CheckDecimalValues(evt) {
var keyCode = evt.keyCode ? evt.keyCode : ((evt.charCode) ? evt.charCode : evt.which);
// 8 Backspace
// 9 Tab key
// 46 Delete
// 35 End Key
// 36 Home Key
// 37 Left arrow Move
// 39 Right arrow Move
if (!(keyCode >= 48 && keyCode <= 57)) {
if (!(keyCode == 8 || keyCode == 9 || keyCode == 35 || keyCode == 36 || keyCode == 37 || keyCode == 39 || keyCode == 46)) {
return false;
}
else {
return true;
}
}
var velement = evt.target || evt.srcElement
var fstpart_val = velement.value;
var fstpart = velement.value.length;
if (fstpart .length == 2) return false;
var parts = velement.value.split('.');
if (parts[0].length >= 14) return false;
if (parts.length == 2 && parts[1].length >= 2) return false;
}
Why don't you use a regex to validate your requirement? 您为什么不使用正则表达式来验证您的需求?
A simple regex like so: 像这样的简单正则表达式:
[0-9]{1}[0-9]{1}[\\.]{1}[0-9]{1}[0-9]{1}
can be used to validate the input without worrying about the key strokes. 可用于验证输入,而无需担心按键。 Just add an
onblur
event on your textbox to validate this. 只需在您的文本框中添加一个
onblur
事件即可对此进行验证。
EDIT: 编辑:
I have added this Fiddle 我已经添加了这个小提琴
Check it out. 看看这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.