3

What is the preferred way to create a button with JSF to call JS function ?

Actually I use :

<p:button onclick="myJSFunction();" href="#"/>

but my urls are suffixed with the anchor symbol (#).

Is there another recommended way to create button which will not reload/navigate to URL but call JS function please ?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Olivier J.
  • 3,115
  • 11
  • 48
  • 71

1 Answers1

5

That's because it's actually navigating to #. You need to block the button from performing its default action, which is navigating to the current view, or to the URL as specified in href or outcome. You can achieve this by adding return false; to the end of onclick.

<p:button onclick="myJSFunction(); return false;" />

Or, if myJSFunction() actually returns a boolean which should determine if the button should continue its default action, then delegate to it:

<p:button onclick="return myJSFunction();" />

The <h:button> works exactly the same way, it's only in standard look'n'feel.

An alternative is to use <p:commandButton type="button">, which generates a real <input type="button"> without any navigation. This way you don't need to return false from onclick.

<p:commandButton type="button" onclick="myJSFunction()" />

This however requires a <h:form> (although placing it outside any form doesn't break any functionality). The same applies to <h:commandButton>.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • mea culpa, you already told me the `return false;` method in another post...and I forgot it ! As always, it's work like a charm, thank you ! – Olivier J. Jan 07 '13 at 22:29