>我有一个文本框字段,我需要允许 18 位或少于 18 位数字且不超过 2 位小数(可能是 1 或 2,但不超过 2(。我该怎么做
小数点前共 18 位数字和 小数点后两位数
<input type="text" name="Txtpercentage"><br>
你可以这样尝试。
$("input[name='Txtpercentage']").on('keydown', function(e) {
var key = e.keyCode ? e.keyCode : e.which;
//alert(key);
if (!([8, 9, 13, 27, 46, 110, 190,17,86].indexOf(key) !== -1 ||
(key == 65 && (e.ctrlKey || e.metaKey)) ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57 && !(e.shiftKey || e.altKey)) ||
(key >= 96 && key <= 105)
)) e.preventDefault();
if ($(this).val().length >= 12) {
var thisVal = $(this).val();
var valtoIns = thisVal.substring(0, 15);
$(this).val(valtoIns);
if (!([8].indexOf(e.keyCode) !== -1)) {
e.preventDefault();
}
}
});
$("input[name='Txtpercentage']").on('keypress', function(e) {
var regex = /.d{2,}/;
var isTwoDecimal = regex.test($(this).val());
//alert(isTwoDecimal);
if(isTwoDecimal){
e.preventDefault();
}
});
查看工作小提琴
希望这有帮助。