0

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?

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

It seems to be a really complicated solution... Why just use the "id" attribute?
As the poster says, he cannot use id, because it is random-generated.
2

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

3 Comments

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.
Could you edit your original post to give an example of such case?
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.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.