使用select2 4.0.3添加所有匹配项

时间:2016-07-11 16:38:46

标签: javascript jquery select2

我想让用户在使用select2时轻松选择所有匹配项。

现有代码

我目前使用select2 4.0.3和jquery 1.11获得以下代码。

<select class="js-example-basic-multiple" multiple="multiple">
  <option value="AL">Alabama</option>
  <option value="AK">Alaska</option>
  <option value="AZ">Arizona</option>
  <option value="WY">Wyoming</option>
</select>
$(".js-example-basic-multiple").select2();

代码https://jsfiddle.net/rwinch/t7112qcc/5/

的完整jsfiddle

我想要的行为

有人可以帮我修改上面的代码,以便用户轻松选择所有匹配项。例如,如果屏幕如下所示:

enter image description here

用户按CTRL + A然后输入,结果为:

enter image description here

1 个答案:

答案 0 :(得分:5)

我已经分道扬琴,所以你可以在这里试试:https://jsfiddle.net/alienpavlov/z34qczr6/1/

$(".js-example-basic-multiple").select2();

$(document).on('keyup', ".select2-search__field", function(e) {
    //if Ctrl+A pressed
    if (e.keyCode == 65 && e.ctrlKey) {
        //Select only filtered results
        $.each($(".select2-results__options").find('li'), function(i, item) {
            $(".js-example-basic-multiple > option:contains('" + $(item).text() + "')").prop("selected", "selected");
        });
        //Remove entered letters and close suggestions
        $(this).val("").click();
        //Select with select2
        $(".js-example-basic-multiple").trigger("change");
    }
});
select {
    width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<p>
    I'd like an easy way for users to add all matches. For example the user
</p>
<ul>
    <li>Enters "A"</li>
    <li>Presses CTRL+A or Meta+A all matches are selected</li>
    <li>Presses enter all matches are added</li>
</ul>
<select class="js-example-basic-multiple" multiple="multiple">
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    <option value="AZ">Arizona</option>
    <option value="WY">Wyoming</option>
</select>

我已将所有评论留在代码中