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>

Check out the Attribute Contains Selector if you're keen on using the ID as the selector. Then you can do something like:

$('input[id*="mycomponentid"]').fadeIn();

Another option is to assign distinct CSS classes to the components you need to interact with in jQuery. I.e.

$('.jsf-username-field').fadeIn();

If you use the later approach, you can allow the framework to generate IDs and you don't even need to bother with them most of the time, especially if you're using a nice AJAX-JSF framework. I favor this approach because it doesn't mingle HTML / JavaScript with JSF.