简体   繁体   中英

Setting focus of input text in a loop

I need to set focus to an h:inputText which is in a component like this:

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

The input text that needs to get the focus is "amountInput." The javascript code I was thinking should do it is

<script>document.getElementById('amountInput').focus()

but it generates the following error: "Cannon call method 'focus' of null." What am I missing?

(I should add that bidView is rendered when the user clicks a Submit button next to each row inside a table. It, bidView, then shows up under that clicked row and allows the user to enter a number and have the server process it.)

The document.getElementById() expects the generated HTML client ID, not JSF component ID. You need to open the page in browser, do rightclick and View Source to see it yourself. Locate the generated HTML <input> element of <p:inputText> and use exactly its id . This ID is prepended with the component ID of every parent NamingContainer component such as <h:form> , <h:dataTable> , <p:tabView> , etc.

You seem to be using PrimeFaces. You can use the p:component() EL function to print the client ID of the given component ID.

<script>document.getElementById("#{p:component('amountInput')}").focus()</script>

An alternative, if you were not using PrimeFaces, is to bind the component to the view and use UIComponent#getClientId() .

<h:inputText id="amountInput" binding="#{amountInput}" value="#{bean.bidAmount}" />
...
<script>document.getElementById("#{amountInput.clientId}").focus()</script>

Coming back to PrimeFaces, are you aware of the <p:focus> component ? You could also use it as well.

<h:panelGroup id="bidView">
    <p:focus context="bidView" />
    ...
</h:panelGroup>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM