Cannot click hidden button by JavaScript

2019-04-17 02:53发布

问题:

function openEditDialog(){
    window.showModalDialog('/atmew/pages/asset/searchInclude/assetEdit.mew');
    document.getElementById('reData').click();
    alert('after rerender');
}

then there is a button:

<a4j:commandLink id="edit" action="#{searchController.openAssetEdit}" 
    oncomplete="openEditDialog()" immediate="true" ajaxSingle="true">
    <h:graphicImage url="/images/edit_icon.png" </h:graphicImage>
    <f:param name="arId" id="arId" value="#{vo.assetReceiving.id}"/>
</a4j:commandLink>

The Other button

<a4j:commandButton id="reData" reRender="data_grid" style="visibility: hidden;" onclick="javascript:alert('rerender clicked');"></a4j:commandButton>

the reData button does not get clicked. The console of IE does not show any message. How is this caused and how can I solve it?

回答1:

You need to use the JSF-generated HTML element ID, not the JSF component ID.

Open the page in browser, rightclick and View Source and locate the JSF-generated HTML <input type="submit"> element of the <a4j:commandButton> in the HTML source. It'll look like this:

<input type="submit" id="someFormId:reData" ... />

You need to use exactly that ID in JavaScript, simply because JavaScript works on the HTML DOM tree, not on the JSF component tree.

document.getElementById('someFormId:reData').click();

Further you'd better be using <a4j:commandLink> instead of <a4j:commandButton> in order to get click() to work.



回答2:

Is it possible to call the onclick via document.getElementById("my-id").click()? At least doing this in Chrome shows me the error "has no method 'click'". Or this possible when using jsf? (EDIT: sorry, might be a stupid question, but I never used jsf)

I think the only reliable way to artificially create a click event on a native node is to do that via browser mechanisms:

function doEvent(element, eventType, event) {
  // modern browsers
  if (document.createEvent) {
    event = document.createEvent("MouseEvents");
    event.initMouseEvent(eventType, true, true, element.ownerDocument.defaultView,
                0, 0, 0, 0, 0, false, false, false, false, 0, null);
    element.dispatchEvent(event);

  // older browsers (IE6/7 for exmaple)
  } else if (element.fireEvent) {
    element.fireEvent("on"+eventType);
  }
}

doEvent(document.getElementById("my-id"), "click");

regarding the ID consider the answer of BalusC