6

I'm trying to force the cursor to go back to its previous input when the value is wrong. Here is a simpler version of the script I use :

$('input:first-child').blur(function(e){
    console.log('here');
  $('input:first-child').focus();
});

It works when I click on another element to focusout but does not when I click on the body or another div element. Why? ​ I have a jsfiddle case : http://jsfiddle.net/leyou/Zabn4/37/

Edit: I was testing on Chrome/Win7, but with Firefox it seems worse. It's totally ignoring focus()

leyou
  • 806
  • 1
  • 13
  • 25
  • It worked for me (Chrome / Win7) :O... – salih0vicX Nov 12 '12 at 15:44
  • Hm. Really strange. It looks like to be focused (outline is set) and 'here' is logged into console when click happens on div or body, but cursor is not moved to focused element... At the same time it works fine after click on some other form element... (win7/chrome) – Viktor S. Nov 12 '12 at 15:47

2 Answers2

7

This happens because the blur has not yet completed. Do it with a small timeout and it would work:

$('input:first-child').blur(function(e){
    setTimeout(function () { $('input:first-child').focus(); }, 20);
});
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
  • 1
    The `change` event would also be like this.Is providing timeout the foolproof solution here?I mean the event could last more then the value 20 in this case. – techie_28 May 05 '16 at 08:30
0

try this

$('input:first-child').blur(function(e){
    console.log('here');
    setTimeout(function() { $('input:first-child').focus(); }, 500);
});
Marlon Vidal
  • 669
  • 4
  • 14