Using Javascript in JSF

By: Andrew Robinson Emailed: 1587 times Printed: 2037 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Is there a place for Javascript with JSF? I would say definitely yes.

One very common scenario is to introduce a confirmation dialog associated with an action (for example deleting a record, canceling an edit). Another common scenario is to perform client side validation thus saving a round trip to the server. An example is to check that the ‘Password’ and ‘Confirm password’ are equal before posting back to the server.

The article describes how to trigger client side javascript functions with the <h:commandLink> and the <h:commandButton> components.

<h:commandLink>

Associating a javascript with a commandLink is not difficult, however in order to do it successfully you need to understand how the <h:commandLink> component is rendered into HTML by JSF.

The example below illustrates how the <h:commandLink> is rendered in HTML:


<h:form id=”userForm”>
<h:commandLink id=”lnkDeleteUser” value=”delete” action=”#{userBean.deleteUser}”/>
</h:form>
<a href="#" onclick=
"clear_userForm();
document.forms['userForm'].elements['userForm:_link_hidden_'].value='userForm:lnkDeleteUser';
if (document.forms['userForm'].onsubmit){
      if (document.forms['userForm'].onsubmit()) 
document.forms['userForm'].submit();
} else {
      document.forms['userForm'].submit();
}
return false;
" 
id="userForm:lnkDeleteUser">delete</a>

There are a few points to note:

  • The <h:commandLink> is rendered as a hyperlink, <a href />

  • The hyperlink itself is “#”; it is basically a dummy value.

  • JSF generates a block of Javascript and it is tied to the ‘onclick’ event. Disregarding the details, it basically calls submit() which post the form to the server.

  • Line 3 is of particular interest – the id of this particular component (“userForm::lnkDeleteUser”) is saved to a hidden field. This is how the JSF engine knows which particular component does the postback and to invoke at the server side actions appropriately.

Most JSF component allows us to inject javascript associated with various client side DHTML events like onclick, ondoubleclick, onfocus etc. With <h:commandLink>, since JSF is already generating Javascript associated with the onclick event, this is where we need to inject our own javascript codes.

The scrpt below illustrates how to inject a line of code to open a confirm dialog window, and the resulting HTML:


<h:form id=”userForm”>
    <h:commandLink id=”lnkDeleteUser” value=”delete” 
            onclick=”if (!confirm('Are you sure you want to delete this record?')) return false”
            action=”#{userBean.deleteUser}”/>
</h:form>
<a href="#" onclick=
"if (!confirm('Are you sure you want to delete this record?')) 
        return false; 
clear_userForm();
document.forms['userForm'].elements['userForm:_link_hidden_'].value='userForm:lnkDeleteUser';
if (document.forms['userForm'].onsubmit){
      if (document.forms['userForm'].onsubmit()) 
document.forms['userForm'].submit();
} else {
      document.forms['userForm'].submit();
}
return false;
" 
id="userForm::lnkDeleteUser">delete</a>

Another important point to note is that the javascript block should not return true under any circumstance. It is does so, the browser will proceed to perform <a href=”#”> – which is redirecting the browser to the dummy “#” page.

<h:commandButton>

The command button is a little simpler. The script below illustrates how to inject a confirmation dialog with <h:commandButton> and how it is rendered in HTML.


<h:commandButton id=”btnCancel” value=”Cancel” 
      onclick=”if (!confirm('You will lose all changes made. Are you sure?')) return false"
/>
<input id="userForm:btnCancel" name="userForm:btnCancel" 
      type="submit" value="Cancel" 
onclick="
if (!confirm('You will lose all changes made. Are you sure?')) return false;
clear_userForm();
"/>

Here the commandButton is rendered as a HTML submit button. If the javascript block returns true then the form is submitted as usual. If it returns false then the form submission is aborted.

The key to successful javascripting with JSF is to understand what is being rendered. Some basic understanding of javascipt goes a long way as well. Also be extra careful with the syntax, as most IDE do not have any support for Javascript. If you made a syntax error - for example missing out a closing bracket, your codes will simply fail silently.


Using javascript and command links to submit a form from a control event

It is quite often that you may want to submit immediately from a control (combo box changes, radio button is selected, etc.). There is no easy way to get a specific action to execute when this happens. One way is via JavaScript and hidden command links.

function clickLink(linkId)
{
  var fireOnThis = document.getElementById(linkId)
  if (document.createEvent)
  {
    var evObj = document.createEvent('MouseEvents')
    evObj.initEvent( 'click', true, false )
    fireOnThis.dispatchEvent(evObj)
  }
  else if (document.createEventObject)
  {
    fireOnThis.fireEvent('onclick')
  }
}

Then add a hidden link to your page (use CSS to ensure it is not visible to the user):

<t:commandLink id="hiddenLink" forceId="true" style="display:none; visibility: hidden;" 
action="#{put your action here}" actionListener="#{put action listener here}">
<!-- parameters, more action listeners, etc. -->
</t:commandLink>

You can see the use of "forceId". The reason for this is that we will be referencing this link using JavaScript and we need the ID and the client ID of a component is not easy to get from a JSF view.

Here is a check box control that will submit on change:

<t:selectBooleanCheckbox value="#{bean value goes here}" onclick="clickLink('hiddenLink');" /> 

JSF Home | All JSF Tutorials | Latest JSF Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(14)


1. View Comment

Problem
The managed bean doesn't get updated when the above javascript is used.


View Tutorial          By: jsfuser at 2007-12-25 22:21:54
2. View Comment

Hello Sir,

Is there a way to use JSF in javascript?
I want to store a value retrieved from a managed bean and trigger a javascript function based on the value.In simple words can I use

var name"#{userAdminBean.lastName}" in javascript function?

Thank You
Rohit


View Tutorial          By: rohit at 2008-04-02 09:07:41
3. View Comment

Is there any way to show the dynamic bean value in the javascript.

i.e, if I am deleting a record, I need to show a confirmation javascript pop-up displaying -- confirmation message with the dynamic row values are are goign to be deleted

How do we do this ?


View Tutorial          By: Bala at 2008-05-04 01:40:18
4. View Comment

Hi, You can use a javascript array. Which means when you are retrieving the records from the database, you can also store the values in the Javascript array. And then when you click the 'Delete' button for example you can call a javascript function and pass the 'array' index as the parameter to retrieve the details and display in the alert.

View Tutorial          By: Mashoud at 2008-05-04 02:54:38
5. View Comment

excellent

View Tutorial          By: alok mishra at 2008-05-12 00:51:57
6. View Comment

Hi,
I have problem of calling javascript function in JSF. I am using Richfaces Components along side.That's why the problem arised.

Can anyone possibly figure out how to overcome the problem of using Richfaces for JSF and also getting the javascript function called for html components.


View Tutorial          By: Shakti Prasad Priyakumar at 2008-06-06 06:11:52
7. View Comment

Great stuff!!!

The clickLink function helped me big time building my solution.
Had to add some portlet namespace stuff as I am working on a 6.0 Portlet project.

Thx


View Tutorial          By: Harro at 2008-10-13 07:25:26
8. View Comment

1==how can we use vb.net web service data in JSF?
2==how to use controls in JSF?


View Tutorial          By: kumaraswamy at 2009-01-06 23:56:53
9. View Comment

This one is helpful. Thanks

Is there any way to change the action of command link and submit form using new action. I tried but not able to do this.

Thanks in advance.


View Tutorial          By: Umesh Aawte at 2009-06-23 06:43:55
10. View Comment

i am converting from Visualbasic 6 to java web app by richface3.3+ spring.
i meet a problem, i can not conver the vb code line to java code, this code line is:
Screen.MousePointer = vbHourglass;
Anyone can help me for this problem!
thanks a lot!


View Tutorial          By: Qui at 2010-01-05 07:26:07
11. View Comment

Thanks - very useful!

View Tutorial          By: Adam Musial-Bright at 2010-02-28 06:14:39
12. View Comment

@ Qui:

You can set the CSS Style:
e.g.:
this.style.cursor = 'wait'"


View Tutorial          By: hache at 2010-06-22 02:02:56
13. View Comment

Hi.

Mi question is more simple. I want to call my sessionDestroyed method in my listener. I have a javascript function which is fired when the user close the browser, in that moment I would like to fire my bean method.

is this possible?

thanks


View Tutorial          By: David at 2010-10-03 04:59:09
14. View Comment

Hi Dear All

How to do strike-out in JSF, if you guys have any idea please give me suggestion.


Thanks In Advance

Sandeep Mehta


View Tutorial          By: Sandeep Mehta at 2012-11-21 06:54:06

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Andrew Robinson
Using Javascript in JSF

More Tutorials in JSF
Struts Vs JSF (A comparison of Struts against JSF)
faces-config.xml to DirectTraffic in the JSF Application
<convertNumber> and <convertDateTime> in JSF
Action listeners in JSF
Calling Multiple Listeners in JSF
Using Javascript in JSF
How to open a new browser window from my JSF page?
Servlet error : java.lang.IndexOutOfBoundsException (JSF RI 1.1_01: IndexOutOfBoundsException)
JSF - TreeNode.setID gets IllegalArgument Exception
Install and Deploy JBoss Application Server
What is JSF (JavaServer Faces)?
Differences between JavaServer Faces technology and Struts
JSF Basics
The Relationship Between JSF and Other Java EE Technologies
JSF Life Cycle

More Latest News
Most Viewed Articles (in JSF )
Install and Deploy JBoss Application Server
How to open a new browser window from my JSF page?
Java Bean Scopes in JSF
Action listeners in JSF
Using Javascript in JSF
Calling Multiple Listeners in JSF
JSF Life Cycle
What is JSF (JavaServer Faces)?
<convertNumber> and <convertDateTime> in JSF
Struts Vs JSF (A comparison of Struts against JSF)
Accessing Context Data in Beans using JSF
JSF Basics
Differences between JavaServer Faces technology and Struts
Installing JSF
Controlling Page Navigation in JSF - Static and Dynamic Navigation
Most Emailed Articles (in JSF)
JSF Basics
JSF Life Cycle
How to open a new browser window from my JSF page?
<convertNumber> and <convertDateTime> in JSF
Calling Multiple Listeners in JSF
Installing JSF
faces-config.xml to DirectTraffic in the JSF Application
Action listeners in JSF
Struts Vs JSF (A comparison of Struts against JSF)
Controlling Page Navigation in JSF - Static and Dynamic Navigation
Using Javascript in JSF
Install and Deploy JBoss Application Server
What is JSF (JavaServer Faces)?
Differences between JavaServer Faces technology and Struts
Java Bean Scopes in JSF