JavaScript Alert Error Message

I am doing a simple validation for the form. Javascript validation works fine, and a popup window appears with the correct errors, BUT, clicking OK, I am redirected to the next page. Ideally, it is assumed that he will remain on the same page so that the user can change their mistakes. Please help, as soon as possible, this is a school project, and the deadline expires in 3 days! :( Thanks in advance.

<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> 
+4
source share
1 answer

This should be an easy fix. In the onsubmit method of your form tag, do the following:

 <form onsumbit="return show_alert();"> 

Instead

  <form onsumbit="show_alert();"> 

Without the return part, a script is run and the form will be submitted anyway. Also, if there is an error condition in the script, you need to add return false; otherwise, the form will still be submitted, and return true; if there is no error. You can edit the script like this:

 <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> 
+3
source

Source: https://habr.com/ru/post/1336606/


All Articles