tags:

views:

154

answers:

3

By default JSF renders the HTML field id name dynamically. ID name is generated randomly in the format formname:id_some_random_number.

Because of this i cannot use document.getElementById("").

Is there any solution for this problem?

+2  A: 

You just need to specify the ID of the input. However, note that the ID will be prefixed by the ID of the form that contains the input field.

For example:

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

the real ID of the inputText is myForm:myInput.

Thus, this Javascript code will work:

var obj = document.getElementById("myForm:myInput");


Edit (for precision)

To be more precise, if a component implements the NamingContainer interface in Java, then all the nested components will have their ID prefixed by the ID of this component. This is the case for the <h:form/> component, but also for <h:datatable/>.

romaintaz
Yup this is how it is working but in some cases like if we embed the component inside another component then the id generated is not predictable.
Madhu
Could you edit your original post to give an example of such case?
romaintaz
This works in my applications. I dont like to use it tho, as if you change any of your components ID's or put them in a different form your javascript will stop working.
ChrisAD
+2  A: 

If all else fails, you can try giving the elements unique css classes and then accessing them via getElementsByClassName(). Or try browsing the childNodes() of an element with known id. Or you can add a node with known id inside your target element and then use .parentNode :)

n1313
It seems to be a really complicated solution... Why just use the "id" attribute?
romaintaz
As the poster says, he cannot use id, because it is random-generated.
n1313
It is random-generated, except if you define yourself the "id" attribute...
romaintaz
+1  A: 

You can get the generated ID by using UIComponent.getClientId (JSF 2, if you can use it, adds a no-arg version that makes this more useful with EL expressions). See this blog post for tips on working with JSF component identifiers (though note the caveats).

McDowell