如何将焦点转移到select2中的下一个元素

时间:2016-03-15 00:51:48

标签: jquery-select2-4

我正在尝试在select2中选择更改时将焦点移到下一个元素上。但我无法做到这一点。 为什么我的焦点不会转移到下一个领域?

html代码

<form>
<select autofocus id="select2" name="entry_id">
    <option value="0">00000000</option>
    <option value="1">11111111</option>
</select>
<input type="text" name="entry_id2" class="entry2">

javascript代码

$("#select2").select2();
$("#select2").on("change", function () {
 $(this).closet("form").find(".entry2").focus();
});

示例页面:https://jsfiddle.net/39wk54zk/

3 个答案:

答案 0 :(得分:0)

这可能不是100%修复,但我注意到在这段代码中,你写的是.closet而不是.closest:

 $(this).closet("form").find(".entry2").focus();

我认为应该是:

 $(this).closest("form").find(".entry2").focus();

我没有测试过,但这可能是你问题的一部分。

答案 1 :(得分:0)

这是使焦点向后或向前移动的完整代码。

      let cursorDirection = ''
    $(document).keydown(function (e) {
        let key = e.which || e.keyCode;
        if (e.shiftKey) {
            //does not matter if user has pressed tab key or not
            cursorDirection = 'prev';
        }
        else if (key == 9) {
            //if tab key is pressed then move next.
            cursorDirection = 'next';
        }
        else {
            cursorDirection == '';
        }
    });
    $(document).ready(function () {
        $('select').select2({
            selectOnClose: true 
        });
        $('.select2-container').focusin(function () {
            try {
                $(this).siblings('select').select2('open');
            } catch (e) {
            }
        });
        $('select').on('select2:close', function () {
            if (cursorDirection == 'next') {
                this.nextElementSibling.nextElementSibling.focus();
            }
            else if (cursorDirection == 'prev') {
                this.previousElementSibling.focus();
            }
        })
    });

答案 2 :(得分:0)

使用tabbable.js尝试一下,我遇到了已经解决的相同问题

$('select').select2({
  placeholder: 'Select a month'
});
$(function() {
  $(document).off('keydown ,select2:close', '.form-control,.select2-search__field')
  jQuery.extend(jQuery.expr[':'], {
    focusable: function(el, index, selector) {
      return $(el).is('a, button, :input, [tabindex]');
    }
  });
  $(document).on('keydown ,select2:close', '.form-control,.select2-search__field', function(e) {

    if (e.which == 13) {
      e.preventDefault();
      jQuery.tabNext();
    }
  });
});

相关问题