jQuery 如何防止在十进制数后按下两位数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15680506/
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
How to prevent keypress two digits after a decimal number?
提问by Monica
I have got a task to prevent keypress two digits after a decimal number. My jquery file is
我有一个任务来防止在十进制数后按下两位数。我的 jquery 文件是
$(function(){
$('#name').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^[a-zA-Z]+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('#salary').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^\d*(\.\d{1,2})+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9]./g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
});
My html page is
我的 html 页面是
<b>Name</b>
<input type="text" id="name" /><br/>
<b>Salary</b>
<input type="text" id="salary" class="decimal" />
here i want only write 2 digits after decimal,how can i do this? You can see my code in http://jsfiddle.net/V6s4B/
这里我只想在小数点后写 2 位数字,我该怎么做?你可以在http://jsfiddle.net/V6s4B/看到我的代码
回答by Daniel Imms
You can handle the key event before keyup
on keypress
, if the input is not to our liking we can disable the event from occurring. Something like this:
您可以在keyup
on之前处理按键事件keypress
,如果输入不符合我们的喜好,我们可以禁用该事件的发生。像这样的东西:
Update
更新
Unfortunately my original answer below fails on certain numbers that can't be represented accurately as a float. Here is another solution that checks the position of the '.'
character against the length of the string with a handy helper function.
不幸的是,我下面的原始答案在某些无法准确表示为浮点数的数字上失败。这是另'.'
一种使用方便的辅助函数检查字符位置与字符串长度的解决方案。
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
e.preventDefault();
return false;
}
});
function hasDecimalPlace(value, x) {
var pointIndex = value.indexOf('.');
return pointIndex >= 0 && pointIndex < value.length - x;
}
Original answer
原答案
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
e.preventDefault();
return false;
}
});
Note that parseFloat(newValue) * 100 % 1 > 0
evaluates to true if newValue
contains a number that has more than 2 decimal places.
请注意,parseFloat(newValue) * 100 % 1 > 0
如果newValue
包含的数字超过 2 位小数,则计算结果为真。
回答by Rick Calder
$("#salary").keyup(function(){
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var salary = parseFloat($("#salary").val());
$("#salary").val( salary.toFixed(2));
}
});
http://jsfiddle.net/calder12/fSQpc/
http://jsfiddle.net/calder12/fSQpc/
Stop letters from going in the box, you'll have to put the two together I haven't time.
不要把信件放进盒子里,你必须把这两个放在一起,我没时间。
if (this.value.match(/[^0-9]./g)) {
this.value = this.value.replace(/[^0-9]./g, '');
return false;
}
回答by Zaheer Ahmed
Another Possible Solution(Demo):
Number.prototype.toFixedDown = function(digits) {
var n = this - Math.pow(10, -digits)/2;
n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
return n.toFixed(digits);
}
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixedDown(2);
}
}
return this; //for chaining
});
});
回答by Quer
This might be helpful to some. I mixed the answers of this guy, @Tats_innit from https://stackoverflow.com/a/10514166/5382523and @Rick Calder above.
这可能对某些人有帮助。我混合了这个人的答案,来自https://stackoverflow.com/a/10514166/5382523 的@Tats_innit 和上面的 @Rick Calder。
EDITalso from this guy, isJustMe from https://stackoverflow.com/a/17289322for the parseFloat with "|| 0". Because if the input's field is null or zero "NaN" is shown and you can't delete it.
编辑也来自这个人,来自https://stackoverflow.com/a/17289322 的isJustMe 用于带有“|| 0”的 parseFloat。因为如果输入的字段为空或零,则会显示“NaN”并且您无法删除它。
HTML
HTML
<input type="text" name="txt_prod_price" id="txt_prod_price" class="form-control price" maxlength="20" placeholder="">
JAVASCRIPT (JQUERY)
JAVASCRIPT (JQUERY)
$('.price').keypress(function(event) {
if(event.which < 46 || event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46 && $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var price = parseFloat($("#txt_prod_price").val()) || 0;
$("#txt_prod_price").val(price.toFixed(2));
}
});
the "price" is pre-defined.
“价格”是预先定义的。
Note: still have buggy inputs but still kickin'. (y)
注意:仍然有错误的输入,但仍然在踢。(y)
More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
有关 toFixed 的更多信息 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
回答by MarwaAhmad
I did it this way: Provided a class allow-only-numbers, for your input then:
我是这样做的:提供了一个类allow-only-numbers,供您输入:
var numberOfDecimals = 2;
$(document).on("input", ".allow-only-numbers", function () {
var regExp = new RegExp('(\.[\d]{' + numberOfDecimals + '}).', 'g')
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '').replace(regExp, '');
});