1

I have some doubt in my mind that if a jsp page onclick() calls a JavaScript method.

I have two scenarios

  1. onclick="return validatePage();"
  2. onclick="validatePage();"

What is the difference between these two types calling of JavaScript methods.

4 Answers 4

2

On the first, by returning the return value of the function, you will cancel the default action for the event when the function returns false. Similar to calling event.preventDefault(). It is notably used when checking for forms validity, where returning false will cancel the form submission.

ps. In the case of form validation, instead of binding the validation function a button's onclick, you should attach it to the form's onsubmit event. This way if the user triggers the submit through pressing Enter on an input, the form will still be checked before submitting.

Sign up to request clarification or add additional context in comments.

2 Comments

Returning false doesn't "cancel the event", it just stops the default action for that element. The event will still propagate if it's an event that propagates (such as click).
@RobG Yes you're right. My initially bad assumption was based on jQuery handlers which by returning false do preventDefault and stopPropagation. I'll update the answer to reword the "cancel" statement.
1

If you return false from the javascript function ,onclick = "return validatePage();" wont submit the form values.

where as, in the case of onclick = "validatePage();" will submit the form values even if you return false from the Javascript function.

1 Comment

Well explained. Thank you so much.
1

For an onclick event those two scenarios are essentially equivalent. The reason you would use "return" is more closely related to an onsubmit event of a form instead of onclick. When you use it with onsubmit, if the function returns false it will prevent the form from being submitted.

Comments

0

Number 1 will return the value, returned by the validatePage(); function. This can be used to interrupt key presses, for example (returning false on the onkeyup of a input field), or to use a anchor (<a href=".... ) as a JavaScript button. Number 2 will simply execute the function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.