wenzhixin / multiple-select

A jQuery plugin to select multiple elements with checkboxes :)
http://multiple-select.wenzhixin.net.cn
MIT License
1.9k stars 652 forks source link

Proposal: Navigation with Arrow Keys and List Close on Enter/Tab in Multiple-Select Component #603

Closed thatisfree closed 8 months ago

thatisfree commented 1 year ago

Hello,

I would like to suggest a couple of modifications to improve the usage of the multiple-select component.

First, I'd like to propose allowing the navigation of the checkbox list using arrow keys instead of the Tab key. Also, when the user hits Enter or Tab, the dropdown list should close. Here's a potential solution:

$(document).ready(function() {
    var $parent = $('.ms-parent');
    var $drop = $('.ms-drop');
    var $choice = $('.ms-choice');
    var $checkboxes = $drop.find('input[type="checkbox"]');

    $choice.on('click', function() {
        $checkboxes.first().focus();
    });

    $checkboxes.on('keydown', function(e) {
        var $this = $(this);
        switch(e.which) {
            case 38: // Up arrow
                e.preventDefault();
                $this.closest('li').prev().find('input[type="checkbox"]').focus();
                break;
            case 40: // Down arrow
                e.preventDefault();
                $this.closest('li').next().find('input[type="checkbox"]').focus();
                break;
            case 9: // Tab
            case 13: // Enter
                e.preventDefault();
                $checkboxes.first().focus();
                $choice.click();
                $choice.focus();
                break;
        }
    });
});

Secondly, I'd like to suggest that when a checkbox receives focus, the closest 'li' element's background changes, indicating which checkbox is currently selected. Here's how I solved this:

// Highlight selected checkbox
$(document).on('focus', 'input[type="checkbox"]', function() {
    $('li').removeClass("hovered");
    $(this).closest('li').addClass("hovered");
});

$(document).ready(function() {
    $("li").hover(
        function() {
            $('li').not($(this)).removeClass("hovered");
                $(this).addClass("hovered");
            }, function() {
                if (!$(this).find('input[type="checkbox"]').is(":focus")) {
                    $(this).removeClass("hovered");
                }
    });
});
wenzhixin commented 1 year ago

Any pull request is welcome.

wenzhixin commented 8 months ago

Fixed in the develop branch.