【问题标题】:jQuery Dropdown - drop down options programmaticallyjQuery Dropdown - 以编程方式下拉选项
【发布时间】:2017-04-17 16:12:31
【问题描述】:

我有一个带有多个选项的选择标签。我有一个用于过滤的搜索框,它根据您键入的文本隐藏或显示选项。我想以与单击它时相同的方式下拉选项,但我想以编程方式进行。我希望有人能理解我想说的话。

换句话说,当用户在搜索文本框中输入内容时,我希望我的下拉元素下拉,用户将能够在输入时看到搜索结果...

我找到了一些<ul><li> 的示例,但我想要<select><option>

HTML

<select id="select_street">
    <option value="1">Street 1</option>
    <option value="2">Street 2</option>
    <option value="3">Street 3</option>
    <option value="4">Street 4</option>
</select>
<input type="text" id="search_filter" />

Javascript/jQuery

$("#search_filter").on('keyup', function (e) {
        $("#select_street option").each(function () {
            if ($(this).html().toLowerCase().includes($.trim($('#search_filter').val()).toLowerCase())) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });

谢谢!

【问题讨论】:

标签: jquery click option dropdown


【解决方案1】:

根据这个answer,这将是您能找到的最接近的解决方案:

$("#search_filter").on('keyup', function(e) {
  $("#select_street").attr('size', $("#select_street option").length);
  //...
});

Example

【讨论】:

  • 我会应用一些淡入淡出效果..会很好。谢谢!
【解决方案2】:

你的代码做你想做的事,但是你必须从隐藏的所有选项开始:

$("#search_filter").on('keyup', function (e) {
    $("#select_street option").each(function () {
        if ($('#search_filter').val() == '') {
            $('#select_street option').hide();
            $('#select_street').val('');
            return;
        }
        if ($(this).html().toLowerCase().includes($.trim($('#search_filter').val()).toLowerCase())) {
            $(this).show();
            if ($('#select_street').val() == '') {
                $('#select_street').val($('#select_street option:first').val());
            }
        } else {
            $(this).hide();
            if ($(this).is(':selected')) {
                $('#select_street').val('');
            }
        }
    });
});
$('#select_street option').hide();
$('#select_street').val('');

没有人使用 select 的原因是您无法以编程方式打开它。我的建议是你选择其中一个https://www.sitepoint.com/13-jquery-selectboxdrop-down-plugins/ 不要试图重新发明轮子。

【讨论】:

  • 好吧...如果我以前知道...谢谢!我有工作要做知道:)
猜你喜欢
  • 2013-08-29
  • 2012-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
相关资源
最近更新 更多