我需要在文本框中插入浮点值,只允许0-9和信号点(。)
我尝试了以下代码:
<html>
<head>
<script type="text/javascript" language="javascript">
function isNumberKey(evt) {
var charCode = (evt.charCode) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
}
</script>
</head>
<body>
<input type="text" id="txtChar" onkeypress="return isNumberKey(event)" name="txtChar" class="CsstxtChar" maxlength="4"/>
</body>
</html>
答案 0 :(得分:0)
jQuery(document).ready(function() {
$('.float-number').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
Enter Number:
<input type="text" name="number" value="" class="float-number">
</body>
</html>
答案 1 :(得分:0)
您可以尝试使用此代码
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="text" id="txtChar" name="txtChar" class="CsstxtChar" maxlength="4" />
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$('.CsstxtChar').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
</script>
</body>
</html>
谢谢
答案 2 :(得分:0)
我建议您改用regexp:
const pattern = new RegExp('[0-9.]');
$('#txtChar').on('keypress', function(e){
const res = pattern.test(e.key);
if(!res) {
e.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txtChar" name="txtChar" class="CsstxtChar" maxlength="4"/>