jquery set focus to dynamically generated element

WallabyKid picture WallabyKid · Jan 26, 2013 · Viewed 8.4k times · Source

I've run into this a number of times, where I wish to reset focus to (and or select the contents of) a dynamically generated element after failing some or other validation (typically on change or blur), but I have never come up with a satisfactory solution. Why won't this work? MyFiddle

jQuery(function(){
    jQuery("body").append("<input type='text' id='test' size='5'/>&nbsp;&nbsp;<button>Go</button>");
    jQuery('body').on('blur', '#test', function()
    {   var test = jQuery(this).val();
        if(test && !isNumber(test))
        {   alert('Not a Number!');
            jQuery(this).focus().select();
            //jQuery('#test').focus().select();
        }
    });
});
function isNumber(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
}

Answer

undefined picture undefined · Jan 26, 2013

You can try using setTimeout function:

$('#test').on('blur', function () {
    var $this = $(this), test = this.value;
    if (test && !isNumber(test)) { 
         setTimeout(function() {
            $this.focus().select();
         }, 4);
    }
});

http://jsfiddle.net/tFAaf/