I have a javascript code that allows me to jump automatically from a form field to the next.
It works using fixed lenght fields.
Example: field TIME can be only 4 numbers, so when the user enters the 4th number, the script focuses on the next field.
It works fine, but I would like to add a feature.
I want to use it in a variable lenght field. My field is composed of LASTNAME (space) First letter of FIRSTNAME.
Example: John Doe will be typed as “Doe J”
The only trick I can think of is to make the field shift when space is pressed + another character is entered. This is the only repeating pattern that would allow the function to be executed with any combination of variable lenght lastnames.
So, any idea how to implement it? I am a beginner in js! Here is the original code:
<SCRIPT TYPE="text/javascript">
<!--
var downStrokeField;
function autojump(fieldName,nextFieldName,fakemaxlength)
{
var myForm=document.forms[document.forms.length - 1];
var myField=myForm.elements[fieldName];
myField.nextField=myForm.elements[nextFieldName];
if (myField.maxlength == null)
myField.maxlength=fakemaxlength;
myField.onkeydown=autojump_keyDown;
myField.onkeyup=autojump_keyUp;
}
function autojump_keyDown()
{
this.beforeLength=this.value.length;
downStrokeField=this;
}
function autojump_keyUp()
{
if (
(this == downStrokeField) &&
(this.value.length > this.beforeLength) &&
(this.value.length >= this.maxlength)
)
this.nextField.focus();
downStrokeField=null;
}
//-->
</SCRIPT>
Rather than detecting a space and then a letter, take a look at the string.match() method.
You can do something like
name.match(/^[A-Z][a-z]* [A-Z]$/)on keypress to determine if name contains a capital letter followed by any number of lower-case letters followed by a space and another capital letter.However, be aware that you may run into issues with your criteria, such as someone who has a title like ‘Jr’, or last names that have spaces, like “Da Silva” or apostrophes, like “O’Malley”. Accommodating the many special cases in peoples names can be tricky.