jquery 通过按键选择 Bootstrap 下拉值

au9on6nz  于 2023-03-17  发布在  jQuery
关注(0)|答案(6)|浏览(167)

我正在使用 Bootstrap btn组下拉菜单作为我的下拉组合框。工作正常。

<div class="btn-group insertText insertTextSMSTemplate">
    <button class="btn btn-small dropdown-toggle" data-toggle="dropdown">Select a Value</button>
    <button class="btn btn-mini dropdown-toggle" data-toggle="dropdown" style='padding:2px;'><span class="icon-chevron-down"></span>
    </button>
    <ul class="dropdown-menu" style="height: 100px; overflow: auto">
        <li><a href="#"></a>
        </li>
        <!-- <li class="divider"></li>
        <li><a href="#">Separated link</a></li> -->
    </ul>
</div>

我编写了一个jquery函数来选择所选的li值并生成按钮文本。
但问题是我的列表很长,我必须在下拉列表中滚动,所以如果我想从下拉列表中选择第70个li元素,我必须向下滚动并选择。
我想给它添加一个功能,如果第70个值是“温度”,那么如果我按“T”,列表中从T开始的单词只显示在下拉菜单中。

gev0vcfq

gev0vcfq1#

jenkilabs代码的修改版本。如果你想循环通过以按键开始的项目,那么使用这个:

$(".dropdown").bind('keydown', function (event) {
            //this will open the list if it is not open and select a value 
            if (event.keyCode != 13){ 
                    if ($(this).find('button').attr('aria-expanded') == 'false')
                    {
                        $(this).find('.dropdown-toggle').dropdown('toggle');
                    }
            }
            var keyChar = String.fromCharCode(event.keyCode).toLowerCase();
            var selectedItems = $(this).find('a').filter(function () {
                return $(this).text().toLowerCase().indexOf(keyChar) === 0;
            });
            var f = $(selectedItems).is(':focus');
            if (f)
            {
                selectedItems = $('a:focus').parent().nextAll().find('a').filter(function () {
                    return $(this).text().toLowerCase().indexOf(keyChar) === 0;
                }).first();
                if (selectedItems.length == 0)
                {
                    selectedItems = $(this).find('a').filter(function () {
                        return $(this).text().toLowerCase().indexOf(keyChar) === 0;
                    });
                }
            }
            selectedItems.first().focus();
        });

ToLowerCase允许你选择以小写字符开始的项目,你不必把以相同字符开头的项目组合在一起,例如。
1.项目a
1.项目a

  1. B
    1.项目a
    这段代码将在第4个位置找到第三个“a”,如果你一直按a,那么它将回到第一个“a”。
    只要这是下拉菜单的结构(见下文),这将起作用。
<div class="dropdown">
      <button class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>
<ul class="dropdown-menu">
 <li><a>text here</a></li>
</ul>
</div>

确保<a>嵌套在<li></li>中,并且<button><ul>周围有class=“下拉”的div

ctzwtxfj

ctzwtxfj2#

我也需要这个。下面是我的Bootstrap 3 focus / select by key input的工作解决方案:

$(".dropdown").bind('keydown', function(event) {
    var keyChar = String.fromCharCode(event.keyCode);
    var selectedItem = $(this).find('a').filter(function(){ return $(this).text().indexOf(keyChar) === 0; }).first();
    selectedItem.focus();
});

说明:其思想是获取列表中的所有可聚焦元素(在本例中为标记),然后通过某种方法过滤它们,以测试按下的键是否是第一个字符。
希望这能帮上忙

fnx2tebb

fnx2tebb3#

我想下面这样的东西应该会起作用。不确定,虽然没有试过跑步。

$("#ID").keydown(function(e){ // the keydown even on ul
    var chr =String.fromCharCode( e.which );
    $(this).find("li").each(function(){ // if the key down is not in UL then make sure the "this" should refer to UL
      var name = $(this).text();
        if( name.toLowerCase().indexOf(chr.toLowerCase()) === 0 ) {
            $(this).focus(); // this should focus you
            return false; 
        }
   });
gmxoilav

gmxoilav4#

如果你对使用插件感兴趣,你可以使用Select2,它非常容易使用,当你初始化select作为select2元素时,它会包含一个搜索栏,当你输入选项时,它会自动过滤选项。
这里有the examples,所以你可以看看你是否喜欢它。

1aaf6o9v

1aaf6o9v5#

我也遇到过同样的问题,我是这样解决的:
首先添加id到ul和按钮然后做以下操作

$('#buttonId').on('keyup', function(){ 
       var key = String.fromCharCode(event.keyCode);
       if(event.which !== 8) {
           keyChar += key;
       } 
       if(event.which === 8) {
          keyChar = keyChar.slice(0, -1);
       }
       var regex = new RegExp('^' + keyChar, 'i');

       $("#ulId li").each(function(){
         if(regex.test($(this).text())) {
            $(this).css("display", "block");
            $(this).addClass('active');
         }else{
            $(this).css("display", "none");
         }
       });
 });
 $('#ulId').on('blur', function(){ 
   keyChar = '';
   });

注意:还将keyChar全局定义为空

waxmsbnn

waxmsbnn6#

当我在最初的问题9年后来到这里时,我想我会提供一个更新的答案。genkilabs答案仍然是完美的,但我想使用香草js,因为jQuery的一切可能现在都可以在香草JavaScript中轻松实现。
我只测试了这为 Bootstrap 4,但由于其基于genkilabs的答案为 Bootstrap 3,它也应该在那里工作。

/**
 * This is a workaround for the fact that Bootstrap 4 dropdowns don't support keyboard navigation.
 */
document.querySelectorAll('.dropdown').forEach(function (dropdown) {
  dropdown.addEventListener('keydown', dropdownKeydownHandler);
});

/**
 * Focuses an <a> element within the dropdown based on matching the key press to the first letter of the link text.
 * @param event - keydown event
 */
function dropdownKeydownHandler(event) {
  const pressedKey = event.key.toUpperCase(); //Assume all our dropdowns are uppercase
  const dropdownDescendants = this.querySelectorAll('a'); //Get all the link elements within the dropdown
  const firstDescendentMatchingKeyPress = Array.from(dropdownDescendants).find((element) => { //turn the NodeList into an array so we can use find()
    return element.innerText.toUpperCase().startsWith(pressedKey); //Find the first link which has inner text starting with the pressed key
  });

  firstDescendentMatchingKeyPress.focus(); //Focus the link
}

如果您遇到原始的下拉切换控件元素被此代码聚焦的问题,那么您可以通过将其添加到find()来排除它

if (element.classList.contains('dropdown-toggle')) //if the link is the dropdown toggle itself, skip it
{
  return false;
}

相关问题