Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is return false and return true used after this inline event-handler?

<button onclick="alert('Hello'); return false;">Hello</button>

What is the return false part supposed to do? Also, what would return true do if it were there?

like image 488
David G Avatar asked Sep 12 '25 04:09

David G


2 Answers

The return false will disregard default behavior for the onclick event. So, for example, if you had a link:

<a href="http://stackoverflow.com" onclick="alert('Hello'); return false">Link<a>

when the user clicks on the link they'd get a popup but wouldn't actually go the target of the link.

like image 68
Rafe Kettler Avatar answered Sep 14 '25 19:09

Rafe Kettler


The default button type is submit, so <button> is the same as <button type="submit"> (except on IE). The return false stops the default button action so it will stop form submission from happening.

You can avoid that by defining the button type explicitly

<button type="button" onclick="alert('Hello');">Hello</button>
like image 34
Mike Samuel Avatar answered Sep 14 '25 18:09

Mike Samuel