Rob Winch Rob Winch - 4 months ago 51
Javascript Question

Add all matches with select2 4.0.3

I'd like to make it easy for user's to select all matches when using select2.

The Existing Code

I currently have the following code using select2 4.0.3 and 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();


A complete jsfiddle of the code https://jsfiddle.net/rwinch/t7112qcc/5/

Behavior I desire

Can someone help me to modify the above code to allow the user to easily select all matches. For example, if the screen looks like:

enter image description here

And the user presses CTRL+A and then enter, then the result is:

enter image description here

Answer

I've forked your fiddle, so you can try it here: 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>

I've left all the comments in the code

Comments