使用jquery在输入字段中进行选项卡

时间:2013-09-17 14:44:40

标签: javascript jquery tabs keypress tabindex

我正在处理一个很好的问题:

我有一个jqueryUI对话框,其中包含3到8个字段:在“TAB”按键上,我希望焦点通过这些字段,按照我之前设置为tabindex html属性的顺序一个接一个地传递。

我在网上看到tabindex属性在浏览器中没有用同样的方式处理..我一直在自己的皮肤上尝试。

所以......问题是:在TAB按键后有没有办法实现这种循环行为?

注意:我不能使用第三方插件..

这是我正在处理的代码:

//... here i set the right values of tabindex to my input fields and then
$.each($array, function (index, elem) {

        var el = elem;

        $(el).on('focus', function (e) {
            $(window).keyup(function (e) {
                var code = (e.keyCode ? e.keyCode : e.which);
                if (code == 9) {
                    var nextIndex = $(el).attr('tabindex') + 1;

                    if (!($('.testPopup').find('input[tabindex=' + nextIndex + ']').length > 0)) {
                        nextIndex = 1;
                    }

                    //using timeout - leaves the event following its default behaviour and completing it
                    setTimeout(function () {
                        $('.testPopup').find('input[tabindex=' + nextIndex + ']').focus();
                    }, 1);
                }
            });
        });
    });

更新

我已经能够改进我以前的解决方案,这是代码:

$(el).on('focus', function (e) {
            $(el).off('keydown').on('keydown', function (e) {

                var code = (e.keyCode ? e.keyCode : e.which);
                if (code == 9) {

                    var nextIndex = $(el).attr('tabindex') + 1;

                    if (!($('.testPopup').find('input[tabindex=' + nextIndex + ']').length > 0)) {
                        nextIndex = 1;
                    }

                    //using timeout - leaves the event following its default behaviour and completing it
                    setTimeout(function () {
                        //Here is the trick which would make my solution working,
                        //but it wouldn't be a flexible reusable solution
                        //$(el).datepicker("hide");
                        $('.testPopup').find('input[tabindex=' + nextIndex + ']').focus();
                    }, 1);

                    //e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
            });
        });

目前问题如下:通过对话框的选项卡将聚焦右下一个输入字段,但其中一个输入字段是jQueryUI日期选择器,它不会自行关闭。如果你查看我更新的代码,你会看到一条注释行$(el).datepicker("hide");,它会使日期选择器关闭..但是,来吧......它是有史以来最糟糕的解决方案..

我知道错误是e.stopPropagation(),但是......我怎么能让它起作用?有什么建议??

1 个答案:

答案 0 :(得分:-1)

您可以使用dom的tabindex属性(此处为输入元素)。

例如: <input type="text" placeholder="User Name" id="username" name="username" value="This is a test" onkeydown="checkEvent(event);" tabindex='1' />