Search code examples
javascriptjsfcallbackcommandbutton

How to click on a p:commandButton using javascript


There are many tag in my JSF page.I want to click a p:commandButton using javascript in one of the forms. But it doesn't work. When I debug it use chrome ,it prompt The p:commandButton can't be found , that is say $("#templetFile\:editButton") is null, why?

There is my code:

<h:form id="templetFile" style="height:100%">
<input type="button" value = "click me" onclick="testOnclick();"/>
<p:commandButton id="editButton" value="ceshi" styleClass="button"
	action="#{advancedQueryManager.editModAndClass()}" onclick="getValddd()"
	style="display:none">
	<p:ajax event="dialogReturn" update="templFile"
	listener="#{advancedQueryManager.onreturn()}" />
</p:commandButton>
		<script type="text/javascript" >
			function testOnclick() {
				var a =$("#templetFile\\:editButton");
				a.click();
			}
			function getValddd(){
				alert("Allready onclick!");
			}
		</script>
  </h:form>

And if I using this js code var b = document.getElementById('editButton'); I still can't get the p:commandButton element.Why?And how to get the p:commandButton using javascript?


Solution

  • Probably, jsf creates a new id for the button so document.getElementById('editButton') does not work. In order to solve this you may add an arbitrary style class to button like;

    styleClass="button myButtonToClick" and javascript should be like this;

    var x =document.getElementsByClassName("myButtonToClick");
    x[0].click();