Home  > Resources  > Blog

Using jQuery With JSF 2.0

 
June 6, 2012 by Bibhas Bhattacharya

Today, I had to finally use both technologies in the same project. You need to do a few things for jQuery to work with JSF 2.0.

  1. Assign ID for all relevant UI components and their parents. Only then can you be sure about the DOM element ID of the component you are trying to manipulate.
  2. Escape the ":" character in the ID.

Let’s learn these two principles using an example. Let’s say, that we have a text box in a form. Make sure both have an ID.

<h:form id="form">
    <h:inputText size="20" value="#{ctrl.dateAsString}" id="dateOfExpense"/>
</h:form>

This means, the text box will have an ID of form:dateOfExpense. If your form has a complicated hierarchy, you can always look at the ID by viewing the source of the page rendered by JSF.

Unfortunately, the ":" character causes havoc in jQuery API. We need to protect it using two back slashes. So, to refer to the text box, we should use the selector "#form\:dateOfExpense". For example, to convert the text box to a jQuery UI date picker, we will do this.

<h:head>
<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
<script type="text/javascript" src="scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="scripts/jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript">
$(function(){
    $("#form\:dateOfExpense").datepicker();
});
</script>
</h:head>

Follow Us

Blog Categories