Use <p:commandLink> just for JS execution without form submit

Gregory picture Gregory · Jun 29, 2015 · Viewed 8.4k times · Source

How can I make <p:commandLink> without submit? Just for JS execution. For <p:commandButton> I can do it this way:

<p:commandButton value="JS button" type="button" onclick="alert('clicked')"/>

What is the analog for <p:commandLink>?

Answer

BalusC picture BalusC · Jun 29, 2015

Just return false from the JavaScript handler.

<p:commandLink ... onclick="alert('clicked'); return false;" />

The same applies to all other on* attributes and the command button, by the way.

<p:commandButton ... onclick="alert('clicked'); return false;" />

Whenever you return false from any JavaScript on* attribute on a HTML element, the element's default action/behavior (in this case, submitting the form) will be blocked.

Nonetheless, if you don't need to invoke a JSF backing bean action method after all, just don't use a command link/button component in first place. Use a plain link/button component.

<h:link ... onclick="alert('clicked'); return false;" />
<p:button ... onclick="alert('clicked'); return false;" />

Those doesn't need to be placed in a form, too.