How can I shift-select multiple checkboxes like GMail?

后端 未结 13 980
野趣味
野趣味 2020-11-30 17:33

In GMail, the user can click on one checkbox in the email list, hold down the Shift key, and select a second checkbox. The JavaScript will then select/unselect the checkboxe

相关标签:
13条回答
  • 2020-11-30 18:10

    I realy liked gyo's example and added some code so it works on all checkboxes with the same name.

    I also added a MutationObserver so events are also handled on newly added checkboxes.

    $(document).ready(function() {
        var previouslyClicked = {};
    
        var rangeEventHandler = function(event) {
            if (event.shiftKey && previouslyClicked[this.name] && this != previouslyClicked[this.name]) {
                var $checkboxes = $('input[type=checkbox][name='+this.name+']').filter(':visible');
                var start = $checkboxes.index( this );
                var end = $checkboxes.index( previouslyClicked[this.name] );
    //              console.log('range', start, end, this, previouslyClicked[this.name]);
                $checkboxes.slice(Math.min(start,end), Math.max(start,end)+ 1).prop('checked', previouslyClicked[this.name].checked);
            } else {
                previouslyClicked[this.name] = this;
            }
        };
    
        if ("MutationObserver" in window) { // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/MutationObserver to refresh on new checkboxes
            var mutationCallback = function(mutationList, observer) {
                mutationList.forEach((mutation) => {
                    mutation.addedNodes.forEach((node) => {
                        if (node.nodeName == 'INPUT' && node.type == 'checkbox') {
                            $(node).on('click.selectRange', rangeEventHandler);
                        }
                    });
                });
            };
    
            var observer = new MutationObserver(mutationCallback);
            observer.observe(document, {
                childList: true,
                attributes: false,  // since name is dynamically read
                subtree: true
            });
        }
    
        $('input[type=checkbox][name]').on('click.selectRange', rangeEventHandler);
    });
    <html>
    <head>
    </head>
    <body>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <div>
        First:
        <input type="checkbox" name="first">
        <input type="checkbox" name="first">
        <input type="checkbox" name="first">
        <input type="checkbox" name="first">
        <input type="checkbox" name="first">
      </div>
      <div>
        Second:
        <input type="checkbox" name="second">
        <input type="checkbox" name="second">
        <input type="checkbox" name="second">
        <input type="checkbox" name="second">
        <input type="checkbox" name="second">
      </div>
    </body>
    </html>

    0 讨论(0)
提交回复
热议问题