我需要将焦点设置为h:inputText,它位于如下组件中:
<h:panelGroup id="bidView">
<h:panelGroup rendered="#{some conditions}">
<h:outputText>
Some text</h:outputText>
<p:inputText id="amountInput" value="#{bean.bidAmount}" />
<h:commandButton value="Submit">
<f:ajax listener="#{bean.submit(item)}" execute="@form" render="bidView "/>
</h:commandButton>
</h:panelGroup>
<script>document.getElementById('amountInput').focus()</script>
</h:panelGroup>
需要获得焦点的输入文本是“amountInput”。我想的javascript代码应该是
<script>document.getElementById('amountInput').focus()
但它会产生以下错误:“Cannon调用方法'焦点'为null。”我错过了什么?
(我应该补充一点,当用户点击表格中每行旁边的“提交”按钮时,会呈现bidView。然后,bidView会显示在该点击的行下,并允许用户输入数字并拥有服务器进程它)。
答案 0 :(得分:4)
document.getElementById()
需要生成的HTML客户端ID,而不是JSF组件ID。您需要在浏览器中打开页面,右键单击查看源以自行查看。找到生成的<input>
的HTML <p:inputText>
元素,并使用其id
。此ID前缀为每个父NamingContainer
组件的组件ID,例如<h:form>
,<h:dataTable>
,<p:tabView>
等。
您似乎正在使用PrimeFaces。您可以使用p:component()
EL函数打印给定组件ID的客户端ID。
<script>document.getElementById("#{p:component('amountInput')}").focus()</script>
如果您没有使用PrimeFaces,另一种方法是将组件绑定到视图并使用UIComponent#getClientId()
。
<h:inputText id="amountInput" binding="#{amountInput}" value="#{bean.bidAmount}" />
...
<script>document.getElementById("#{amountInput.clientId}").focus()</script>
回到PrimeFaces,你知道the <p:focus>
component吗?你也可以使用它。
<h:panelGroup id="bidView">
<p:focus context="bidView" />
...
</h:panelGroup>