views:

54

answers:

3

Here is something so simple

<p:commandLink value="Tom" onclick="document.getElementById('tom').focus()"/><br/>
<input id="tom"/>

When u click on the Tom, the textbox get focus. Great, now try this

<p:commandLink value="Tom" onclick="document.getElementById('tom').focus()"/><br/>
<h:inputText id="tom"/> <br/>

when I click nothing happen, I check firebug, I see

document.getElementById("tom") is null

When I try to use jQuery $('#tom').focus(), nothing happen, no error, but did not get focus either. This is the response (not sure if this is the response from the server) when I see from firebug

<?xml version="1.0" encoding="utf-8"?>
<partial-response>
    <changes>
       <update id="javax.faces.ViewState"><![CDATA[455334589763307998:-2971181471269134244]]></update>
    </changes>
    <extension primefacesCallbackParam="validationFailed">{"validationFailed":false}</extension>
</partial-response>

+1  A: 

You need to give that JSF tag an id attribute, like this:

<h:inputText id="tom" />

Otherwise it won't render with an id, and so there will be no id="tom" element to find.

Nick Craver
I have that `id="tom"` in my code, it is a typo. Thank you
Harry Pham
@Harry - what does the rendered html look like?
Nick Craver
Actually I figure out what wrong. Outside of these commandLink is a form which will prepend its `id` to its child, so instead of id `tom` it is now become `j_idt7:tom`. If I `document.getElementById('j_idt7:tom')` then it works. jQuery actually smarter, if I do $('#tom'), it does not say that element `tom` is null, but it does not get focus either. :(
Harry Pham
@Harry - You can do `$("input[id$=tom]")` for IDs that end in "tom"...or give it a class instead and use that selector, e.g. `class="tom"` and `$(".tom")`.
Nick Craver
+1  A: 

In JSF, the ID of elements are prefixed by the ID of the form that contains them (more generally, their ID are prefixed by the ID of all the parent components that implements the NamingContainer interface). For example:

<h:form id="myForm">
    <h:inputText id="tom" .../>

will generate the following HTML code:

<input id="myForm:tom" ...>

To access the <input> you must use the myForm:tom ID and not the tom ID itself.

With jQuery, you will have to use $("myForm\:tom").focus();

romaintaz
+1  A: 

JSF will prepend ID's of UINamingContainer children (h:form, h:dataTable, etc) with the ID of the UINamingContainer component itself. You can disable this by setting the prependId attribute to false.

<h:form prependId="false">

You only won't be able anymore to dynamically include the same piece of code somewhere else in the same view. Keep this in mind when disabling this.

BalusC