Submit button getting disabled automatically after onSubmit event returns false with alert. Later on, onchange event also not able to enable it.
Below is the javascript and HTML
On submitting form without checkbox, an alert is popped and the submit button gets disabled. On checking the box Submit button cant enable it back. How can i ensure submit button to remain enabled or onchange event to enable it?
Any leads are appreciated.
<script type="text/javascript">
function checkme() {
if (!document.form.agree.checked) {
missinginfo = "You must agree to the condition\n 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>
`
First, you should consider moving your event listening to your script instead of using onSubmit()
Then you can select your input and button on the script, and add an event listener to your input, so every time it changes, it checks if the checkbox is checked or not (checkBox.checked). If it is not checked, it disables the button (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>