我有一个任务来限制文本框的字母值。仅浮点值是可能的。小数点后,我们必须写出两位数。我这样做了,但是在Mozilla Firefox中不起作用。我怎么解决这个问题?
我的剧本是
$(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').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;
}
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
else {
var len = document.getElementById("txtChar").value.length;
var index = document.getElementById("txtChar").value.indexOf('.');
if (index > 0 && charCode == 46) {
return false;
}
if (index >0 || index==0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 3) {
return false;
}
}
}
return true;
}
});
HTML是
<b>Name</b>
<input type="text" id="name" /><br/>
<b>Salary</b>
<input type="text" id="txtChar" onkeypress="return isNumberKey(event)" name="txtChar" class="CsstxtChar" />
最佳答案
function isNumberKey(evt) {
var charCode = (evt.charCode) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
else {
var len = document.getElementById("txtChar").value.length;
var index = document.getElementById("txtChar").value.indexOf('.');
if (index > 0 && charCode == 46) {
return false;
}
if (index >0 || index==0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 3) {
return false;
}
}
}
return true;
}
<input type="text" id="txtChar" onkeypress="return isNumberKey(event)" name="txtChar" class="CsstxtChar" />