How to call JS function on click of JSF button and block page reload/navigation?

蹲街弑〆低调 提交于 2019-12-12 03:36:19

问题


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:


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



来源:https://stackoverflow.com/questions/36087914/how-to-prevent-commandbutton-from-executing-action-when-onclick-method-return-fa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!