Setting the focus to a form field

The Set cursor focus snippet in the EGL drawer of the Snippets view is a JavaScript function that sets the cursor focus to a specified form field on a web page. It must be placed within a <script> tag in a JSP page.

To insert and configure this snippet:

  1. Add a <script> tag within the <head> tag of the JSP file as in this example:
    <script type="text/javascript">
    <!-- snippet code goes here -->
    
    </script>
  2. From the EGL drawer of the Snippets view, drag the Set cursor focus snippet to a blank line within the <script> tag you just added. For more information, see Inserting code snippets into EGL and JSP files. This snippet goes into the code of the JSP file, not the code of the JSF Handler part.
  3. In the snippet code, replace both instances of [n] with the number of the form field which will receive focus. The form fields are numbered beginning with zero. For example, use [3] to set focus to the fourth field on the page.
  4. In the snippet code, replace both instances of form1 to the value of the ID attribute of the form to which you want to set focus.
  5. In the <body> tag of the JSP page, add the attribute onload="setFocus();" as in the following example:
    <body onload="setfocus();">
  6. Save the file.
The code inserted by this snippet is as follows:
function setFocus() {
 document.getElementById('form1').elements[n].select();
 document.getElementById('form1').elements[n].focus(); 
}

Feedback