简体   繁体   中英

How to call a function AFTER blur from input?

I'm using jquery-ui datepicker as one of my inputs. If a user blurs from an input, I display a relevant message (eg "This field is required"). For this purpose I have the following jQuery, which works perfectly fine for simple <select> and <input type="text"> tags:

$("input").blur(function(){
    if($(this).val()=="")
        $(this).next().text("This field is required.");
    else
        $(this).next().text("");
});

However, in case of datepicker (where I have to essentially blur to select a date) the error message gets displayed even after I've selected the date (ie selection of date is leading to the blur event). This requires that the .blur(function(){}); should be called after the blur event is completed (not simultaneously).

How to solve this situation?

Here's a DEMO .

You could add your validation check to the onClose event of the datepicker, rather than the blur event of the input field:

$("#datepicker").datepicker({onClose: function(selectedDate) {
    if(!selectedDate) {    
        $(this).next().text("This field is required.");
    }
}});

Kind of a hack, but you could just delay the check with setTimeout :

$("input").blur(function () {
    var $t = $(this);
    setTimeout(function () {
        if ($t.val() == "") $t.next().text("This field is required.");
        else $t.next().text("");
    }, 100);
});

http://jsfiddle.net/D4AGz/96/

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