javascriptjsf-2faceletsmanaged-bean

How to trigger hidden JSF commandLink in JavaScript?


I have a similar question on this thread where I have a JavaScript function which will trigger the click event of a hidden commandLink. And the hidden command will fire the action in Java Bean. This code is working fine in IE, but not in Firefox. Is there any clue on this issue?

JavaScript

<h:outputScript target="head">
    HTMLElement.prototype.click = function() {
    var evt = this.ownerDocument.createEvent('MouseEvents');
    evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
    this.dispatchEvent(evt);
  }

  function triggerHiddenEvent() {
    alert("triggerHiddenEvent is trigger");
    document.getElementById("theForm:hiddenCommand").click();
  }
</h:outputScript>

XHTML

<h:form id="theForm">
  <h:commandLink id="tri_HiddenEvent" value="Trigger Hidden Event" onclick="triggerHiddenEvent"/>

  <p style="display:none">
    <h:commandLink id="hiddenCommand" styleClass="button" action="#{helloBean.doHiddenCommand}"/>
  </p>
  ...

The Bean

@ManagedBean
@SessionScoped
public class HelloBean implements Serializable {
  public String doHiddenCommand() {
    System.out.println("doHiddenCommand is called");
    return "";
  }
}

Solution

  • change

    onclick="triggerHiddenEvent"

    into

    onclick="triggerHiddenEvent(); return false;"

    you need to add the return false; snippet in order to stop the page from submitting/reloading...

    h:commadLink Tag:

    This tag generates HTML’s <a href link tag and some JavaScript functions which make the link to act as a submit button. To prevent page submission, you have to explicitly add simple return false; to your onclick function

    Difference Between h:commandButton , h:commandLink and h:outputLink in JSF