您可以使用此代码
<form>
<input type="text" id='myField' />
<input type="submit" id="submit" value="Submit" />
</form>
<script>
var myField = document.getElementById('myField');
myField.addEventListener('input', function (prev) {
return function (evt) {
if (!/^\d+(?:\.\d{0,2})?$/.test(this.value)) {
this.value = prev;
this.style.borderColor = 'red';
this.style.fontWeight = 'bold';
document.getElementById('submit').disabled = true;
}
else {
prev = this.value;
this.style.borderColor = '';
this.style.fontWeight = '';
document.getElementById('submit').disabled = false;
}
};
}(myField.value), false);
</script>
(编辑)
根据您的评论,我编辑了适用于多个领域的答案。只需在输入字段中添加一个类名即可在 javascript 中处理
<form>
<input type="text" class='decimalField' />
<input type="text" class='decimalField' />
<input type="text" class='decimalField' />
<input type="submit" id="submit" value="Submit" />
</form>
<script>
var decimalField = document.getElementsByClassName('decimalField');
for(var i = 0; i<decimalField.length; i++){
decimalField[i].addEventListener('input', function (prev) {
return function (evt) {
if (!/^\d+(?:\.\d{0,2})?$/.test(this.value)) {
this.value = prev;
this.style.borderColor = 'red';
this.style.fontWeight = 'bold';
document.getElementById('submit').disabled = true;
}
else {
prev = this.value;
this.style.borderColor = '';
this.style.fontWeight = '';
document.getElementById('submit').disabled = false;
}
};
}(decimalField[i].value), false);
}
</script>