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>
You can put your form validation against this event type. The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the web server. If validate() function returns true, the form will be submitted, otherwise, it'll not submit the data.
It means that do nothing on submit.
The onsubmit handler is not called, because the form cannot be submitted by any normal means, i.e. the submit event cannot be caused. There is only one submit control, and it is declared as disabled.
Yes, the form is required to have an action attribute in HTML4. If it's not set, the browser will likely use the same method as providing an empty string to it. You really should set action="" which is perfectly valid HTML4, follows standards, and achieves the same exact result.
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>
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