myfaces-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Bryan Basham <>
Subject Re: Javascript and JSF
Date Fri, 25 May 2007 16:32:30 GMT
Hello Balaji,

Yes, I do this all the time.  Remember in XHTML you have access to the
complete DOM of the screen including form fields created by JSF components
(which render as HTML form components, ultimately).

Suppose that you have a form that has a drop-down list that (when selected)
adds some boiler-plate text to a text field:

<h:form id='x'>
  <select name='type' onselect='javascript:selectType(this);'>
    <option name='BUG'>Bug report</option>
    <option name='RFE'>Request for enhancement</option>
  <h:inputText id='title' value='#{bean.entryTitle}' />

NOTE: this code I am making up on the fly and is not be completely accurate.
This is just an abstraction of what could happen in "real life".  Note 
also that
in this example, I am mixing non-JSF HTML components (the <select> tag)
with JSF components (the <h:inputText> tag).  I did this on purpose to 
that there is nothing magically about JSF components after they are 
rendered to
the browser.

So, the JS function 'selectType' is invoked whenever the user selects a 
new option.
Let's see how this function can change the value of the text field:

<script ...>
function selectType(selectField)
  var type = selectField.currentOption.value;  // OK, this JS code is 
way off, but you get the idea
  var textField = document.getElementById('x:title');
  textField.value = type + ": Enter title here";

OK, so what the hell am I talking about?  Well, the critical element in this
JS fuction is the use of "document.getElementById()" function which is built
in to client-side JavaScript language.  This function as you might guess 
the HTML component by its ID anywhere within the DOM for the screen.
Note that the ID for the text field is 'x:title' which is the form ID 
'x' prepended
to the inner text field ID 'title'.  So, that is how you can access (as 
an object)
any form field (really *any* HTML element) and then manipulate that element
object in real-time.

Now the trick is: *What* do  you want to do with the form element after you
have retrieved it from the getElementById function?  There are lots of ways
to manipulate form elements: hide/show, disable/enable, change the value,
change the style or class, and so on.  You will need to learn JavaScript in
more detail to answer these types of questions.  Good luck!

I see that others are focusing on AJAX.  Please note that you do *not* 
have to
use AJAX to use the technique I described above.  However, AJAX extends 
techniques by allowing your client-side JS code to make calls to the server.


Balaji Saranathan wrote:
> Hi,
> Is it possible to capture a JavaScript event and update a selected JSF 
> component on the page?
> Regards
> Balaji

View raw message