Pergunta

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);
}
Foi útil?

Solução

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/

Outras dicas

What happens if you try this:

$(function(){
    $("body").append("<input type='text' id='test' size='5'/>&nbsp;&nbsp;<button>Go</button>");

    $('#test').on('blur', function() {   
        if (isNaN(this.value)) {   
            alert('Not a Number!');
            $(this).focus();
        }
    });
});

If the element has no value when the user toggles out of the element, it focuses it and raises an alert. This is what you want, no?

this:

jQuery('body').on('blur', '#test', function()

should be:

jQuery(document).on('blur', '#test', function()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top