0

I am fairly new to Javascript and have a basic question. I have an HTML form with first_name and last_name input fields. I have the following Javascript code in the header but after the code runs, the focus goes to the next field (last_name). Why is that and how do I correct it?

Thank you.

<script>
        function validateForm()
        {
            valid = true;

            //validate first name
            if (document.contactform.first_name.value == "")
            {
                //alert user first name is blank
                alert("You must enter a first name");
                document.getElementById("first_name").focus();
                return false;
            }
            return valid;
        }
    </script>   

and the form field code is: input type="text" name="first_name" id="first_name" maxlength="50" size="30" onBlur="validateForm()"

Wally Fisher
  • 39
  • 2
  • 8

1 Answers1

0

A fix for this is to add a slight delay.. like so:

setTimeout(function() {
    document.getElementById('first_name').focus()
}, 10);

Here is your example with this fix in jsfiddle: http://jsfiddle.net/FgHrg/1/

It seems to be a common Firefox problem.. I don't know exactly why but it has something to do with Firefox loading the javascript before the DOM is fully loaded.. in otherwords getElementById('first_name') returns null. But adding the slight delay fixes this problem.

Bryan Elliott
  • 4,055
  • 2
  • 21
  • 22
  • Thank you. I see how the code works but is there a generic way to return the user to the field that called the function? It seems that if there was 8 or 10 fields and you were validating each one, this would be redundant code. Thanks. – Wally Fisher Sep 14 '13 at 22:38
  • Unfortunately I have not found any other fix for this. but I did find that the setTimout can actually be set to 0, instead of 10 (as it is in the above code) and it still works. You could also check out this: http://stackoverflow.com/questions/7046798/jquery-focus-fails-on-firefox – Bryan Elliott Sep 15 '13 at 00:57