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.
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
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.
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.
Posted at 10:55AM May 25, 2008 | Permanent link to this entry