Victor
Victor

Reputation: 297

jquery tabIndex fix

On my pages(ASP.NET 3.5) where all input controls have tab order set whenever next input control is not enabled or hidden it goes to the address bar and then to next available control. To fix this behavior, i.e. make it land to the next available control w/o going to address bar I am trying to use jQuery:

$(':text,textarea,select').blur(function()
{
    $(this).next(':text, textarea, select').filter(':enabled:visible').focus();        

});  

But it still goes to the adress bar in some cases. What do I need to correct here?

Upvotes: 0

Views: 3167

Answers (1)

Nick Craver
Nick Craver

Reputation: 630429

Let me start off by saying, I wouldn't do this, but instead use the tabindex property on your controls to get the tab order you want, the address bar only being at the very end since that's what a user expects.

That being said, there is a jQuery way to force what you want, you can do something like this:

$('form :input:enabled:visible').blur(function() {
  var con = $(this).closest('form').find(':input:enabled:visible');
  var i = con.index(this);
  setTimeout(function() { con.eq(i == con.length - 1 ? 0 : i + 1).focus(); }, 0);
});

This changes a few things:

  • .next() only looks for the very next element
    • This looks up to the <form> and gets the next match (change form to body for all inputs).
  • The tab needs to wrap around to the first element when reaching the end
    • Use .index() and i == con.length - 1 ? 0 : i + 1 for this
  • Last, the focus event of the landing element will fire after this blur (by default)
    • To fire immediately after that use a setTimeout(func, 0) like above

Upvotes: 1

Related Questions