我的任务是防止在十进制数后的两位数上按键。 我的 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);
});
});
我的html页面是
<b>Name</b>
<input type="text" id="name" /><br/>
<b>Salary</b>
<input type="text" id="salary" class="decimal" />
这里我只想写小数点后两位数,我该怎么做? 你可以在 http://jsfiddle.net/V6s4B/ 中看到我的代码
最佳答案
您可以在 keypress
上的 keyup
之前处理按键事件,如果输入不符合我们的喜好,我们可以禁止该事件发生。像这样:
更新
不幸的是,我下面的原始答案在无法准确表示为 float 的某些数字上失败。这是另一个解决方案,它使用方便的辅助函数检查 '.'
字符的位置与字符串的长度。
$('.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;
}
原始答案
$('.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;
}
});
请注意,如果 newValue
包含超过 2 位小数的数字,则 parseFloat(newValue) * 100 % 1 > 0
计算结果为 true。
关于javascript - 如何防止按键十进制数后的两位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15680506/