I want to run JavaScript user validation on some textbox entries.
The problem I’m having is that my form has the action of going to a new page within our site, and the onsubmit
attribute never runs the JavaScript function.
Is there a better solution, or one that works with the following code: Note: the JavaScript file is written correctly and works if you switch the action to checkRegistration()
.
It is merely an issue with running both action and JavaScript.
<form name="registerForm" action="validate.html" onsubmit="checkRegistration()" method="post"> <!-- Textboxes are here --> <!-- And the submit button --> </form>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You should stop the submit procedure by returning false on the onsubmit callback.
<script> function checkRegistration(){ if(!form_valid){ alert('Given data is not correct'); return false; } return true; } </script> <form onsubmit="return checkRegistration()"...
Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:
<script> function checkRegistration(){ var form_valid = (document.getElementById('some_input').value == 'google'); if(!form_valid){ alert('Given data is incorrect'); return false; } return true; } </script> <form onsubmit="return checkRegistration()" method="get" action="http://google.com"> Write google to go to google...<br/> <input type="text" id="some_input" value=""/> <input type="submit" value="google it"/> </form>
Method 2
Try
onsubmit="return checkRegistration()"
Method 3
Try:
onsubmit="checkRegistration(event.preventDefault())"
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0