Click here to Skip to main content
15,444,490 members
Articles / Auto-complete
Posted 22 Jul 2013


26 bookmarked

Select2 - The Ultimate jQuery Autocomplete

Rate me:
Please Sign up or sign in to vote.
4.79/5 (20 votes)
23 Jul 2013CPOL4 min read
The ultimate jQuery Autocomplete solution. Infinite scrolling by remote data source, as well as quick and easy searching.


I have looked at a lot of of the AJAX autocomplete options available, but most of them fall short in one way or another.

Your options were either:

  1. Load a small amount of data on the page and let JavaScript filter it (the user can still scroll through the data).
  2. Load large amounts of data by searching through AJAX queries (but the user cannot scroll through the data).

You could not do both...until now. Try out a live demo of the solution on my website.

This is made possible by the Select2 jQuery autocomplete plugin. Although it has very good documentation I still had some trouble getting it up and running in a .NET MVC environment. To make this a little easier to get started with (and to encourage more people to use this fantastic plugin), I decided to put together a sample MVC project that uses this solution.


This article assumes a familiarity with jQuery and with .NET MVC. If you are accessing someone else's JSON service, you just need the jQuery experience, but if you need to create the front and back end it would help to be familiar with .NET MVC as well.

This project was built using Visual Studio 2012 Express. You can download Visual Studio Express for free if you do not have it.

Select2 settings and code examples can be found on their site.

The demo project requires NuGet to be installed, since it re-downloads the required dependencies for the project to run.

The code is also available for download on GitHub.

Using the code

JavaScript Includes

To get started, download the latest version of jQuery as well as the CSS and JavaScript for Select2. Both of these can also be downloaded via NuGet inside Visual Studio.

<link href="~/Content/css/select2.css" type="text/css" rel="stylesheet" />
<script src="~/Scripts/jquery-2.0.3.js"></script>
<script src="~/Scripts/select2.js"></script> 

To get this working on the front end, you will need:

  1. A textbox with an id to identify it. This is the area on the page where Select2 will load the results of your json query.
  2. The URL of your JSON service. This is where we will look for more data for the dropdown.
  3. To configure the settings to determine how you want this to work (delay before running the query, how many results to return, etc.

The core of the JavaScript is here:

//The url we will send our get request to
var attendeeUrl = '@Url.Action("GetAttendees", "Home")';
var pageSize = 20;

    placeholder: 'Enter name',
    //Does the user have to enter any data before sending the ajax request
    minimumInputLength: 0,            
    allowClear: true,
    ajax: {
        //How long the user has to pause their typing before sending the next request
        quietMillis: 150,
        //The url of the json service
        url: attendeeUrl,
        dataType: 'jsonp',
        //Our search term and what page we are on
        data: function (term, page) {
            return {
                pageSize: pageSize,
                pageNum: page,
                searchTerm: term
        results: function (data, page) {
            //Used to determine whether or not there are more results available,
            //and if requests for more data should be sent in the infinite scrolling
            var more = (page * pageSize) < data.Total; 
            return { results: data.Results, more: more };

And our html textbox where we will store the data looks like this:

<input id="attendee" name="AttendeeId" type="text" value="" />

That's really all that is needed on the front end to get this going. Things get a little more involved if you have to setup the backend as well, but it's nothing we can't handle.

Setting Up the JSON Service

We need to send the data from our backend to Select2 in a certain format. Basically we need to send an id and text value for each result returned. We also need to return the total count of all the results that are returned.

This is so when we start scrolling through the data Select2 knows if it needs to keep requesting more data or if we are at the end of our results.

So the classes we'll create to hold our results look like this:

public class Select2PagedResult
    public int Total { get; set; }
    public List<Select2Result> Results { get; set; }
public class Select2Result
    public string id { get; set; }
    public string text { get; set; }

Our method that returns the JSON is going to go to our data store, get any attendees that match the search term typed into the dropdownlist, and is then going to convert that data into the Select2PagedResult class, which it will then send back to the browser as our JSON result.

public ActionResult GetAttendees(string searchTerm, int pageSize, int pageNum)
    //Get the paged results and the total count of the results for this query. 
    AttendeeRepository ar = new AttendeeRepository();
    List<Attendee> attendees = ar.GetAttendees(searchTerm, pageSize, pageNum);
    int attendeeCount = ar.GetAttendeesCount(searchTerm, pageSize, pageNum);

    //Translate the attendees into a format the select2 dropdown expects
    Select2PagedResult pagedAttendees = AttendeesToSelect2Format(attendees, attendeeCount);       

    //Return the data as a jsonp result
    return new JsonpResult
        Data = pagedAttendees,
        JsonRequestBehavior = JsonRequestBehavior.AllowGet

All the code to get test data from our data store, search through the first and last names in the last, and convert the results to a Select2PagedResult class is included in the sample project.


Is it worth going through all this effort? If you have small lists of data, probably not. For lists with 100 items or less in them, the default JavaScript filtering in Select2 is fast enough and is much easier to setup (just a few lines of code).

In my demo example, the code is filtering a list with 1000 attendees quickly and easily, since all the heavy lifting is done by the server and the JavaScript only has to display 20 results at a time. In cases like this, setting up Select2 with a remote data source will be worth the time you put in.


  • 7/22/2013 - Posted code.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior)
United States United States
I am a .Net developer with over 10 years experience.

Check out my latest project, True Novelist

Comments and Discussions

QuestionNot compatible with .NET Core Pin
MSDEVTECHNIK11-Oct-20 6:59
MemberMSDEVTECHNIK11-Oct-20 6:59 
GeneralMy vote of 5 Pin
Moslem.Hady18-Oct-16 20:06
MemberMoslem.Hady18-Oct-16 20:06 
it is awesome. thank you so much Smile | :)
QuestionAdd event onSelect Pin
Member 26867312-Oct-16 11:43
MemberMember 26867312-Oct-16 11:43 
Questionselect2 js error Pin
Laurentiu LAZAR29-Sep-16 4:06
MemberLaurentiu LAZAR29-Sep-16 4:06 
QuestionDropdownlist instead of textbox Pin
IAmDineshL10-May-16 0:41
professionalIAmDineshL10-May-16 0:41 
Questionhow to display search box, select multiple options and ajax load Pin
p.divya11226-Feb-16 19:11
Memberp.divya11226-Feb-16 19:11 
GeneralMy vote of 4 Pin
Liju Sankar28-Nov-15 13:30
professionalLiju Sankar28-Nov-15 13:30 
QuestionHow can i add a new attribute ? Pin
Sinan Yalcinkaya12-Jun-15 2:19
MemberSinan Yalcinkaya12-Jun-15 2:19 
SuggestionAccessing Results in JSON in ASP .NET WebMethod Pin
Rocky#15-May-15 4:33
MemberRocky#15-May-15 4:33 
GeneralRe: Accessing Results in JSON in ASP .NET WebMethod Pin
Rajan Patekar29-Mar-18 5:19
professionalRajan Patekar29-Mar-18 5:19 
Questionis this possible for jquery categories(catcomplete) Pin
hasbina12-Mar-15 2:31
Memberhasbina12-Mar-15 2:31 
GeneralMy vote of 5 Pin
JasonMacD18-Aug-14 3:52
MemberJasonMacD18-Aug-14 3:52 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun12-Mar-14 22:49
MemberHumayun Kabir Mamun12-Mar-14 22:49 
GeneralMy Vote 5 Pin
ketan207-Oct-13 23:07
Memberketan207-Oct-13 23:07 
QuestionWeb Forms Example Pin
Member 79720044-Oct-13 20:14
MemberMember 79720044-Oct-13 20:14 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun23-Jul-13 1:03
MemberHumayun Kabir Mamun23-Jul-13 1:03 
GeneralRe: My vote of 5 Pin
Neil Meredith23-Jul-13 5:42
MemberNeil Meredith23-Jul-13 5:42 
GeneralMy vote of 5 Pin
Antariksh Verma23-Jul-13 0:58
professionalAntariksh Verma23-Jul-13 0:58 
GeneralRe: My vote of 5 Pin
Neil Meredith23-Jul-13 5:42
MemberNeil Meredith23-Jul-13 5:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.