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 ?

1 Answer 1

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>.

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

1 Comment

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 !

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.