onSubmit事件返回false并发出警报后,Submit按钮将自动禁用。稍后,onchange事件也无法启用它。
下面是javascript和HTML
在提交不带复选框的表单时,会弹出一个警报,并禁用提交按钮。选中"提交"按钮后,无法将其启用。我如何确保提交按钮保持启用状态或更改事件以启用它?
任何线索都将不胜感激。
<script type="text/javascript">
function checkme() {
if (!document.form.agree.checked) {
missinginfo = "You must agree to the conditionn Please tick the checkbox and try again.";
alert(missinginfo);
return false;
}
else {
return true;
}
}
</script>
<form name="form" id="form" action="/gl" onSubmit="return checkme();" method="post">
<input type="checkbox" id="agree" onchange="document.getElementById('submit-form').disabled = !this.checked;"/> I AGREE
<div class="row">
<div class="col-sm-4 col-sm-offset-8 col-md-3 col-md-offset-9 input-group">
<button type="submit" value="Submit" class="btn btn-primary" id="submit-form">Submit</button>
</div>
</div>
`
首先,您应该考虑将事件移动到脚本中,而不是使用onSubmit()
然后,您可以在脚本上选择输入和按钮,并在输入中添加一个事件侦听器,因此每次更改时,它都会检查复选框是否选中(checkBox.checked
(。如果未选中,则禁用按钮(button.disabled = !checkBox.checked;
(
const checkBox = document.getElementById("agree");
const button = document.getElementById("submit-form");
checkBox.addEventListener("input", () => {
button.disabled = !checkBox.checked;
});
<form name="form" id="form" action="/gl" onSubmit="return checkme();" method="post">
<input type="checkbox" id="agree" /> I AGREE
<div class="row">
<div class="col-sm-4 col-sm-offset-8 col-md-3 col-md-offset-9 input-group">
<button disabled type="submit" value="Submit" class="btn btn-primary" id="submit-form">
Submit
</button>
</div>
</div>
</form>