Main Tutorials

How to get JSF id via jQuery

See a simple JSF example :


<h:form id="signup-form">
    <h:inputText id="email" value="#{beanBean.email}" />
</h:form>

It will generates following HTML code :


<input id="signup-form:email" type="text" />

Uses jQuery selector to get the email id, but failed.


<script>
   jQuery(document).ready(function($) {
		
	$('#signup-form:email').checkEmailFormat();		
		
   });
</script>

Solution

This is a well-known problem to integrate JSF and jQuery – the colon “:” is reserved for jQuery selector. To use jQuery seletor to get the JSF id, you need to “escaped” the colon by placing two backslashes in front of it :


<script>
   jQuery(document).ready(function($) {
		
	$('#signup-form\\:email').checkEmailFormat();		
		
   });
</script>

For PrimeFaces

PrimeFaces comes with a function to escape the JSF id :


<script>
   jQuery(document).ready(function($) {
		
	$(PrimeFaces.escapeClientId('signup-form:emil')).checkEmailFormat();
		
   });
</script>

This PrimeFaces.escapeClientId function is from primefaces.js, review the source code, it’s just a wrapper js function to replace the colon “:” with placing a double backslashes in front of it.

primefaces.js

escapeClientId:function(a){return"#"+a.replace(/:/g,"\\:")}

P.S Tested with PrimeFaces 3.3

References

  1. jQuery selector
  2. How do I select an element by an ID that has characters used in CSS notation?
  3. jQuery – get id of an element
  4. Id’s from JSF, used in jQuery
  5. jQuery, JSF ids and PrimeFaces

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Flavio
8 years ago

JESUS TY, GOD TY

Tayfun
8 years ago

Please remove $ in ur javascript code.

Efraim Salazar
9 years ago

And how do you do an ‘alert’ whith jQuery and JSF?

ND
10 years ago

As an alternative, you can also just use some css class name like so:
.myCSSClass{}

which ends up in HTML as

so that you can get the id as:

var elementId = $(‘.someClassName’);

ND
10 years ago
Reply to  ND

Correction to previous comment, the css class defined like so:

.myCSSClass{}

The JSF like so:

which ends up in HTML as:

so that you can get the id as:

var elementId = $(“.myCSSClass”);

Luca
11 years ago

Or, you can change the separator char:

<context-param>
    <param-name>javax.faces.SEPARATOR_CHAR</param-name>
    <param-value>-</param-value>
</context-param>