Search code examples
javascriptjqueryfocusonblur

jQuery focus after onblur using "this"


I have several fields that need to check for a minimum value after onblur and return to the field if the value is not correct. $(this).focus() does not seem to work.

$(".PartMin").blur(function()
{
    var Value = this.value.replace("$", "");
    if(Value < 115)
    {
        alert("Value cannot be less than $115.00");
        $(this).focus();
    }
});

Solution

  • Setting focus in blur callbacks is often problematic. I've found introducing a delay helps:

    $(".PartMin").blur(function()
    {
        var Value = this.value.replace("$", "");
        if(Value < 115)
        {
            alert("Value cannot be less than $115.00");
            var element = this;
            setTimeout(function() {
              $(element).focus();
            }, 50);
        }
    });
    

    Live Example (doens't work with Stack Snippets because of the snippet UI).


    But: I strongly recommend not doing intrusive validation (popping up an alert) on blur. Let the user move around fields, and provide non-intrusive feedback (colors, etc.), and only intrusive feedback when they try to confirm an action using the data.