Unable to restrict focus to a textbox for input error

Unable to restrict focus to a textbox for input error

Hi,
 
I am trying to restrict focus to a textbox if there is input error, but with no success. Here is my javascript:
  1. $(document).ready(function () {
        $("#txt_username").blur(function () {
            var username_length;

  2.         username_length = $("#txt_username").val().length;
            $("#username_warning").empty();
  3.         if (username_length < 4) {
                $("#username_warning").append("Username is too short");
                $("#txt_username").focus();
            }
        });
    });





 
and html:
  1. <form id="form1">
            <div>
                <b>Username:</b> <i>Username must be at least 4 characters in length</i>
                <br /><input type="text" id="txt_username" name="username" />
                <span id="username_warning" style="color:red"></span>
            </div>
            <div>
                <b>Password:</b> <i>Password must be at least 6 characters in length</i>
                <br /><input type="password" id="txt_password" name="password" />
                <span id="password_warning" style="color:red"></span>
            </div>
            <div>
                <input type="submit" value="Submit"/>
            </div>
    </form>













txt_username never gets focus when it is shorter than 4 characters. How do I make it happen?
 
TIA