Friday, June 16, 2006

OnBlur Javascript recursive loop

Recently some of the developers in my team were struggling with a javascript issue.
The problem was very simple. There were 2 textfields on the screen - one after the other. Both of which have an OnBlur call to a routine that simply validates that the fields are not left blank.

Now when the first field is left blank and a 'tab' is pressed, then the javascript goes into a recursive loop !!! The loop is started because we used the focus method in the javascript function: tabbing out of field one fires onblur and sets focus to field two. The function focusses back to field one, "taking focus off field two", which fires a new onblur, which makes your function put focus back on field two firing onblur for field one. This goes on forever.

The solution to this is very simple - Just keep a global variable that points to the current object being validated and check that inside the function. Here is the script for doing so:

var currentObjectName='';

function NoBlank(object, label)
{
if (currentObjectName!=''; currentObjectName!= object.name) return;

currentObjectName=object.name;

if (object.value == "")
{
lc_name = label;
alert(lc_name + " input field cannot be blank!")
object.focus();
return false;
}

currentObjectName='';
return true;
}

No comments:

Post a Comment