Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML form action and onsubmit issues

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> 
like image 626
James Brown Avatar asked Apr 28 '13 12:04

James Brown


People also ask

How do you handle Onsubmit in 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.

What happens when Onsubmit returns false?

It means that do nothing on submit.

Why Onsubmit is not being called?

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.

Do HTML forms need an action?

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.


1 Answers

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> 
like image 161
s3m3n Avatar answered Sep 19 '22 18:09

s3m3n