简体   繁体   中英

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();
    }
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM