Handle Large Data in Select2 Dropdown

Objectives of the blog

After the reading of this blog, you will able to know how you can handle the large set of data in the Select2 dropdown menu.

Description  

For a dropdown, if use the select2 library, it works really well for the small number of data but when the data become too large then you can face the issue of slowness. For example, suppose a dropdown of 20,000 options then the select2 library can take up to some seconds to minutes to open the dropdown. For such a large dropdown menu and to avoid this slowness issue, select2 provides an alternate solution.

In the normal select2 dropdown, we use <select> element. In the <select> element, select2 library binds all options in one go and this is causing the slowness for the large data. So instead of using the <select> element, you can use the textbox dropdown and select2 library helps to bind the textbox as the dropdown menu so it will give the fill of the dropdown menu to the users. The select2 library can smartly bind user-defined 20 or 30 options at a time and remaining data will binds either on search or on the scroll.

Running code is given below.

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
        <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.min.css" />
        <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-css/1.4.6/select2-bootstrap.min.css" />
        <style>
            .select2-container-multi .select2-choices .select2-search-choice {padding: 5px 5px 5px 18px;}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="page-header">
                <h1>Select2 Dropdown menu with pagination</h1>
                <p>To improved performance of the dropdown with large data sets (20 000 items)</p>
            </div>
            <form method="post">  
                <input id="test" style="width:100%;" placeholder="type a number, scroll for more results" name="data" />
                <input type="submit" value="Submit" name="Submit" class="btn btn-info"/>
            </form>
        </div>
        <script type="text/javascript" src='//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.min.js"></script>
        <script>
            (function () {
                // initialize select2 dropdown
                $('#test').select2({
                    data: dropdownData(),
                    placeholder: 'search',
                    multiple: true,
                    // creating query with pagination functionality.
                    query: function (data) {
                        var pageSize,
                                dataset,
                                that = this;
                        pageSize = 20; // Number of the option loads at a time
                        results = [];
                        if (data.term && data.term !== '') {
                            // HEADS UP; for the _.filter function I use underscore (actually lo-dash) here
                            results = _.filter(that.data, function (e) {
                                return e.text.toUpperCase().indexOf(data.term.toUpperCase()) >= 0;
                            });
                        } else if (data.term === '') {
                            results = that.data;
                        }
                        data.callback({
                            results: results.slice((data.page - 1) * pageSize, data.page * pageSize),
                            more: results.length >= data.page * pageSize,
                        });
                    },
                });
            })();
            // Function to fetch the demo data for the dropdown menu
            function get_random_word(str) {
                return str
                        .split('').sort(function () {
                    return 0.5 - Math.random();
                }).join('');
            }
            // For the testing purpose we are making a huge array of demo data (20 000 items)
            function dropdownData() {
                return _.map(_.range(1, 20000), function (i) {
                    return {
                        id: i,
                        text: get_random_word('The quick brown fox jumps over a lazy dog') + ' ' + i,
                    };
                });
            }
        </script>
    </body>
</html>

 

Output Screen

Handle Large Data in Select2 Dropdown
Summary

When user will submit this form, system will get the selected data in an array.

Sunny Saurabh

Sunny Saurabh

Sunny Saurabh is an experienced Software engineer in C# and ASP.NET as well as an expert as a PHP developer. He has also expert in database design, server maintenance and security. He has achieved this goal only in the short span of 3yrs and still looking forward to achieving more in the IT industry. He lives in New Delhi and his hobby to write the technical writeups.

Leave a Reply

Your email address will not be published. Required fields are marked *