Search code examples
jquerysetfocusdynamic-content

jquery set focus to dynamically generated element


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

Solution

  • 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/