VW tip: Automatically setting focus to next form element

Assume, you have three text field as shown below and user needs to type three number in each field.

        Phone Number : - -

After typing 3 numbers in the first field, to type in the next field, user first clicks on the second field to get the keyboard focus in that field and then types the numbers. However, it is possible to write a small JavaScript snippet to make the focus automatically jump to next field for the user. Known as form field AutoTab.

Using Netbeans Visual Web, first I created the following fields

  • Dropped the Woodstock Layout -> GridPanel and in the property sheet set the columns to 4.
  • Dropped Woodstock Basic -> Label and selected labelLevel -> Strong(1) in the property sheet.
  • Dropped three Woodstock Basic -> Text Fields and set
    • columns = 5
    • maxLength = 3

Next step is to create the necessary JavaScript. Added the following to the <head> section in the JSP.

   <script type="text/javascript">
function autotab(tabFrom, tabToId){
var length = tabFrom.value.length;
var maxLength = tabFrom.getAttribute("maxlength");
if (length == maxLength){
var tabTo = document.getElementById(tabToId);
tabTo.focus();
}
}
</script>

The script takes two parameters.

  • tabFrom - The field from which the focus should jump from
  • tabTo - The "id" of the field to which the focus should jump to

Next step is to call this JavaScript from a suitable event in the TextField. To do this, selected the TextField in the designer and from the property sheet scrolled down to JavaScript event list and entered the following code to the "onKeyUp" event.

 autotab(this, 'form1:textField2_field')

In the above snippet, "this" refers to the field from which the focus should jump and "form1:textField2_field" is the id of the field to which the focus should jump to.

Note: The id of a JSF component specified in the JSP is not same as the id of the HTML dynamically generated in the browser. So it is important to use tools like firebug to find the correct id.

Deployed the application and typed three numbers. When I typed the third number, the focus automatically automatically jumped to the next field.
 

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today