Javascript 使用 jQuery 将输入字段限制为两位小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10570722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Restrict input field to two decimals with jQuery
提问by Ismailp
I have an input field which I want to restrict so that the user only can input a number with the maximum of two decimals. Want to do this using jQuery.
我有一个我想限制的输入字段,以便用户只能输入最多两位小数的数字。想要使用 jQuery 来做到这一点。
Could I use jQuery toFixed()function somehow?
我可以以某种方式使用 jQuery toFixed()函数吗?
Thanx!
谢谢!
回答by sabithpocker
$('input#decimal').blur(function(){
var num = parseFloat($(this).val());
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
if(num/cleanNum < 1){
$('#error').text('Please enter only 2 decimal places, we have truncated extra points');
}
});
Here is a fiddle http://jsfiddle.net/sabithpocker/PD2nV/
这是一个小提琴http://jsfiddle.net/sabithpocker/PD2nV/
Using toFixed
will anyhow cause approximation 123.6666 -> 123.67
If you want to avoid approximation check this answer Display two decimal places, no rounding
toFixed
无论如何使用将导致近似123.6666 -> 123.67
如果你想避免近似检查这个答案显示两位小数,不四舍五入
回答by Tegge
An alternative approach with a regular expression:
使用正则表达式的另一种方法:
$('#id').on('input', function () {
this.value = this.value.match(/^\d+\.?\d{0,2}/);
});
The id selector can be replaced by a css selector.
id 选择器可以替换为 css 选择器。
回答by Oriol
A HTML5 solution:
HTML5 解决方案:
<input type="number" step="0.01" />
If you want to style invalid inputs (some browsers do it by default), you can use :invalid
selector:
如果你想设置无效输入的样式(一些浏览器默认这样做),你可以使用:invalid
选择器:
input:invalid { box-shadow: 0 0 1.5px 1px red; }
Note this approach won't attempt to truncate the number automagically, but if the user enters more than two decimal digits, the input will become invalid, and thus the form won't be submitted:
请注意,此方法不会尝试自动截断数字,但如果用户输入超过两位十进制数字,则输入将无效,因此不会提交表单:
回答by jawaharlal
<input type="text" name="amount1" id="amount1" class="num_fld Amt" onkeypress="return check_digit(event,this,8,2);" size="9" value="" maxlength="8" style="text-align:right;" />
The following function will restrict decimals according to your need of decimal places and also restrict more than one dot
以下功能将根据您对小数位的需要限制小数,也限制一个以上的点
function check_digit(e,obj,intsize,deczize) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) { keycode = e.which; }
else { return true; }
var fieldval= (obj.value),
dots = fieldval.split(".").length;
if(keycode == 46) {
return dots <= 1;
}
if(keycode == 8 || keycode == 9 || keycode == 46 || keycode == 13 ) {
// back space, tab, delete, enter
return true;
}
if((keycode>=32 && keycode <=45) || keycode==47 || (keycode>=58 && keycode<=127)) {
return false;
}
if(fieldval == "0" && keycode == 48 ) {
return false;
}
if(fieldval.indexOf(".") != -1) {
if(keycode == 46) {
return false;
}
var splitfield = fieldval.split(".");
if(splitfield[1].length >= deczize && keycode != 8 && keycode != 0 )
return false;
}else if(fieldval.length >= intsize && keycode != 46) {
return false;
}else {
return true;
}
}
}
回答by Lidor
$("#myInput").focusout(function() {
if ($(this).val().length > 2 || isNaN(Number($(this).val())) {
alert("Wrong number format");
}
});
回答by PawlikDoc
Try this for all symbols:
对所有符号试试这个:
inputField.value.replace(/(\...)(.)/, "$1");
inputField.value.replace(/(\...)(.)/, "$1");
or this for numbers:
或者这对于数字:
inputField.value.replace(/(\.[0-9][0-9])([0-9])/, "$1");
inputField.value.replace(/(\.[0-9][0-9])([0-9])/, "$1");
I found this method here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Example:_Switching_words_in_a_string
我在这里找到了这个方法:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Example: _Switching_words_in_a_string
回答by Heinrich
<input type="text" id="decCheck" onkeyup="decimalCheck();"/>
<script>
function decimalCheck(){
var dec = document.getElementById('decCheck').value;
if(dec.includes(".")){
var res = dec.substring(dec.indexOf(".")+1);
var kl = res.split("");
if(kl.length > 1){
document.getElementById('decCheck').value=(parseInt(dec * 100) /
100).toFixed(2);
}
}
}
</script>
回答by Soumava Das
A similar solution with a backspace hit on reaching more than 2 decimal places.
一个类似的解决方案,在达到超过 2 个小数位时使用退格键。
function limitDec(id) {
// find elements
var amt = $("#testdec")
// handle keyup
amt.on("keyup", function() {
if (isNaN(amt.val())) {
amt.val(0);
}
if (amt.val().indexOf(".") > -1 && (amt.val().split('.')[1].length > 2)) {
amt.val(amt.val().substring(0, amt.val().length - 1));
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="text" id="testdec" onkeyup="limitDec(this.id)" />