C.J.
C.J.

Reputation: 6879

Contain tabbing to a form using jQuery

How best could you use jQuery to limit tabbing to a container such as a form. When the last input control of the container is reached I'd like hitting tab to cycle back to the 1st input control in the container.

The only way to escape this "tab group" would be to click outside of it.

The reason I wish to do this is because I have several forms in the DOM but some are off screen (to the right). They only slide in to view when needed.

The problem is in FF when someone tabs beyond the visible form and goes to the off screen form the off screen form pops into view and this is very undesirable.

I'd appreciate any help. Thanks.

Upvotes: 0

Views: 160

Answers (2)

spirytus
spirytus

Reputation: 10946

Wow, yet another tabbing issue. I had similar problem and created tiny jQueryUI plugin that limits fields that TAB affects. you use it simply:

$(".someGroup").tabGuard();

and that will make tab iterate over fields inside of .someGroup wrapper. This way you can group various forms on a page and the one in focus will keep iterating on TAB or Shift+TAB if that makes sense. Find it here:

http://tomaszegiert.seowebsolutions.com.au/tabguard/index.htm

I hope someone will find it useful.

Upvotes: 1

C.J.
C.J.

Reputation: 6879

I was able to get basically what I needed using jQueryUI. Here's my 1st draft:

(function ($)
{
    $.widget("ui.tabLock",
    {
        options:
        {
            selector: ":tabbable" //jQuery selector for finding tabbable controls
        },

        _create: function ()
        {
            //Store 1st & last tabbable control
            var c = $(this.options.selector, this.element);
            this.firstCtrl = c.eq(0);
            this.lastCtrl = c.last();

            this._wireEvents();
        },

        destroy: function ()
        {
            $.Widget.prototype.destroy.call(this);   //jqueryUI 1.8
        },

        _wireEvents: function ()
        {
            var self = this;

            //Cycle on last input
            this.lastCtrl.on("keydown." + this.widgetName, function (e)
            {
                if (e.which === 9 && !e.shiftKey)
                {
                    self.firstCtrl.focus();
                    return false;
                }
            });

            //Cycle on first input
            this.firstCtrl.on("keydown." + this.widgetName, function (e)
            {
                if (e.which === 9 && e.shiftKey)
                {
                    self.lastCtrl.focus();
                    return false;
                }
            });
        }
    });

} (jQuery));

Upvotes: 1

Related Questions