I'm doing a simple validation for a form. The JavaScript validation works fine and the pop up alert box appears with the correct errors, BUT, upon clicking "Ok", I get re-directed to the next page. Ideally, it is supposed to stay at the same page so that the user can amend his/her mistakes.
This is a school project.
<script type = "text/javascript">
function show_alert() {
if (document.getElementById('time1').value == document.getElementById('time2').value) alert("ERROR! You cannot book the same timing twice!")
else if (document.getElementById('time1').value == document.getElementById('time3').value) alert("ERROR! You cannot book the same timing twice!")
else if (document.getElementById('time1').value == document.getElementById('time4').value) alert("ERROR! You cannot book the same timing twice!")
else if (document.getElementById('time1').value == "0") alert("ERROR! You cannot leave the first time slot blank!")
else {}
}
</script>
This should be easy to fix. In the onsubmit method of your form tag, do this:
<form onsumbit="return show_alert();">
Instead of
<form onsumbit="show_alert();">
Without the return part, the script will run, and the form will be submitted anyhow. Also, if there is an error condition in the script, you need to add a return false; otherwise the form will still be submitted, and return true; if there is no error. You can edit the script like so:
<script type = "text/javascript">
function show_alert() {
if (document.getElementById('time1').value == document.getElementById('time2').value) {
alert("ERROR! You cannot book the same timing twice!");
return false;
} else if (document.getElementById('time1').value == document.getElementById('time3').value) {
alert("ERROR! You cannot book the same timing twice!");
return false;
} else if (document.getElementById('time1').value == document.getElementById('time4').value) {
alert("ERROR! You cannot book the same timing twice!");
return false;
} else if (document.getElementById('time1').value == "0") {
alert("ERROR! You cannot leave the first time slot blank!");
return false;
} else {
return true;
}
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With