Jump to content

onsubmit="return validateForm()"


davej

Recommended Posts

In my code I have not had any use for the onsubmit event. When my javascript initializes I just change the submit button into an ordinary button and then have the onclick event call the validation function which may or may not submit the form. But I would like to understand this example... http://www.w3schools.com/js/js_form_validation.asp Apparently onsubmit="return function1()" gives function1 the ability to cancel the submittal by returning a false value. Is this approach in any way better than what I am doing? Are there yet other ways to control form submittal on the client side? Thanks.

Link to comment
Share on other sites

  • 1 year later...

I have not tested this but it would be the same as...

<form name="myForm" action="demo_form.asp" onsubmit="validateForm();return false;" method="post">

...which of course has to do with the cancellation of the default action.

Link to comment
Share on other sites

if the function() already returns false, why do we need to add another return there ?

Because the code inside the attribute is basically its own function, which runs in the scope of the element with the attribute on it. When that event handler actually runs it's something more like this:
function() {  validateForm();}
If there's no return statement, then the event handler doesn't return anything to cancel the default action. Adding the return statement fixes that:
function() {  return validateForm();}
Now the event handler returns a value.
Link to comment
Share on other sites

You have not mentioned that you are relying on someone clicking the button that you are using for submit, they could easily bypass this by hitting the return/enter key while in a input field. Where as if you use onsubmit you would catch this.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...