4

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);
}
WallabyKid
  • 503
  • 2
  • 5
  • 16

3 Answers3

4

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/

Ram
  • 143,282
  • 16
  • 168
  • 197
1

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?

hohner
  • 11,498
  • 8
  • 49
  • 84
  • Not sure what you've changed beyond removing.select(), but no, it doesn't work. That's where I started. Edit, my bad... you've alterend the event handler... let me test in fiddle and get back. – WallabyKid Jan 26 '13 at 14:15
  • This event handler won't work as the element is dynamically appended. The OPs orignal `on()` signature was correct. – Rory McCrossan Jan 26 '13 at 14:19
  • Well... color me surprised, as the event handler actually works in the fiddle (I didn't think it would either), however the focus still doesn't – WallabyKid Jan 26 '13 at 14:24
0

this:

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

should be:

jQuery(document).on('blur', '#test', function()
ROY Finley
  • 1,406
  • 1
  • 9
  • 18