I have a submit button like this:
<input class="create_button" name="commit"
onclick="return validate_activity();"
type="submit" value="Save">
I found that this button will always send request to the server whatever the validate_activity() return true or false?
What's the problem here?
UPDATE
Actually, I made a mistake in my validate_activity(), it makes me think it returned false, but it not.
This blog emphasize to onsubmit event in JavaScript. When a user clicks on submit button of a form, JavaScript onsubmit event will call a function. In our example, we call ValidationEvent() function on form submission. That will first validate the form fields and will return a boolean value either true or false.
The formnovalidate attribute is a boolean attribute. When present, it specifies that the form-data should not be validated on submission. This attribute overrides the form's novalidate attribute. The formnovalidate attribute is only used for buttons with type="submit" .
<input type="submit"> buttons are used to submit forms.
JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two functions. Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in.
try doing same without return, e.g. onclick="validate_activity();"
and check if your function returns false in case of invalidity
Try this...
<form action="...." onsubmit="submitForm()" name="form">
<input type="submit" value="Save">
</form>
function submitForm(){
if(validationfails){
return false;
}
else {
document.form.submit();
return true;
}
}
<input type="button" name="commit"
value="Save"
onclick="validate_activity(myform)" />
Inside the Javascript, when validated, do form.submit()
or else return false.
I hope this helps ! This will validate your form and submit it. This submit will fail if the Javascript is disabled in your browser.
if you want the submit to proceed even if the javascript is disabled in the client browser ( means no validation but will submit), then
<input type="button" name="commit"
value="Save"
onclick="validate_activity(myform);return false;" />
I hope no validation shouldn't hit you at all. But then javascript is just client side and I hope you will have serious sanity checks on the server side anyways and of many, I think people use it for very basic field checks.
You should use the submit
event of the form for validation..
<form action="..." method="..." onsubmit="return validate_activity()">
<...>
<input class="create_button" name="commit" type="submit" value="Save" />
<...>
</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