« July 24, 2006 | Main | August 2, 2006 »

July 27, 2006 Archives

July 27, 2006

Reset button doesn't empty fields


The <af:resetButton> component: doesn't empty the fields after a Form was submitted.
Instead, it reverts them to their values right after the last Form submission.

If you want to empty the values in the Form elements, you have to use JavaScript.

Suppose a JSF page with a field identified as 'username':

<af:inputText label="Username" (...) id="username"/>

The following example nullifies it
 function resetFields() {
   document.forms[0].elements['username'].value='';  
}

A more generic JavaScript function, working for all fields in a Form, but also for other types of widgets (list & checkbox) could be:
function moreGenericResetFields() {
   for ( i=0; i < document.forms[0].elements.length; i++) {
      if ( ! ( document.forms[0].elements[i].readOnly  || document.forms[0].elements[i].disabled) ) {

         if (( document.forms[0].elements[i].type == 'text' ) || ( document.forms[0].elements[i].type == 'textarea' ) || ( document.forms[0].elements[i].type == 'password' )) {
            document.forms[0].elements[i].value = '';
         }

         if ( document.forms[0].elements[i].type == 'checkbox' ) {
            document.forms[0].elements[i].checked = false;
         }

         if ( document.forms[0].elements[i].type == 'select-one' && ( document.forms[0].elements[i].length != 0 )) {
            document.forms[0].elements[i].options[0].selected = true;
         }

      }
   } 
}
You can save the JavaScript function in a file, eg utils.js and reference it from a <script> tag in the <afh:head>:
(...)
<afh:head>
  <script src="utils.js" type="text/javascript"></script>
  (...)
</afh:head>
<afh:body>
  (...)
  <af:inputText label="Username" (...) id="username"/>
  (...)
  <af:commandButton text="Reset Via JavaScript" onclick="resetFields()"/>
  (...)
</afh:body>
(...)

I've added example  #2 in my sample page.

About July 2006

This page contains all entries posted to Didier's Blog in July 2006. They are listed from oldest to newest.

July 24, 2006 is the previous archive.

August 2, 2006 is the next archive.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type and Oracle