How to refer to a JSF component Id in jquery? [duplicate]

You can give all NamingContainer components in the view such as <h:form>, <h:dataTable>, <ui:repeat>, <my:composite> a fixed ID so that the HTML-generated client ID is safely predictable. If you’re uncertain, just open the page in webbrowser, rightclick and do View Source. If you see an autogenerated ID like j_id123 in the client ID chain, then you need to give exactly that component a fixed ID.

Alternatively, you can use #{component.clientId} to let EL print the component’s client ID to the generated HTML output. You can use component’s binding attribute to bind the component to the view. Something like this:

<h:inputText binding="#{foo}" />
<script>
    var $foo = $("[id='#{foo.clientId}']"); // jQuery will then escape ":".
    // ...
</script>

This only requires that the script is part of the view file.

As another alternative, you could give the element in question a classname:

<h:inputText styleClass="foo" />
<script>
    var $foo = $(".foo");
    // ...
</script>

As again another alternative, you could just pass the HTML DOM element itself into the function:

<h:inputText onclick="foo(this)" />
<script>
    function foo(element) {
        var $element = $(element);
        // ...
    }
</script>

Leave a Comment