Saturday, July 4, 2015

Ajax Call by search string in Select2 auto complete

Select2 is nice Javascript plug in to create dropdown which supports lot of event and very much flexible too.  Few days ago I got requirement where I had to create one dropdown with search facility . I mean we need to pull data based on search string of user and bind to dropdown.

Select2 support ajax functionality too. Here is sample code to implement ajax


$(document).ready(function () {

                                var pageSize = 20;

                                jQuery(".select2").select2({
                                    placeholder: "Select value ...",
                                    allowClear: true,
                                    ajax: {
                         //How long the user has to pause their typing before sending the next request
                                        quietMillis: 150,
                                        url: '../CollegePlacement/Result',
                                        data: function (term, page) {
                                            return {
                                                pageSize: pageSize,
                                                pageNum: page,
                                                searchTerm: term
                                            };
                                        },
                                        results: function (data) {

                                            return {
                                                results:
                                                    data.map(function (item) {
                                                        return {
                                                            id: item.Id,
                                                            text: item.CompanyName
                                                        };
                                                    }
                                            )
                                            };

                                        }
                                    }
                                })

                            });


Please have a look on result callback of function. The column name which is coming as collection has Id and CompanyName field. We are just mapping this with default column name of select2 which is “id” and “text”


Here is sample output. 


No comments:

Post a Comment