Sunday 8 September 2013

Restricting Number of Suggestions in jQuery UI Auto Complete Using Underscore.js

jQuery UI’s autocomplete widget can be used with an array of objects or we can take complete control with by defining a function that emits the list of suggestions to be displayed. Restricting the count of suggestions to a given number is slightly tricky. There are several ways to skin this cat. In this post, we will see one of the ways to achieve the same using Underscore.js.

To make the number of suggestions configurable, a data- attribute can be used.

<input type="text" id="txtName" data-count="5" placeholder="Your name..." />

We need to define a source function to take control over suggestions to be displayed and filter data from the collection using underscore.js and value of the data-count attribute on the element. The source function should perform the following tasks:
  • Select a list of entries from the collection that contain the term entered using _.filter() function
  • Take first n(n being value of data-count attribute) entries from the filtered list using _.take() function
  • Pass the values selected in step 2 to response

var names=["Alex", "Andrew", "Andrea", "Anna", "Abbie", "Abraham", "Aisha", "Albert", "Albina", "Alisha", "Barbie", "Bailey", "Barton", "Bernardo", "Blaise", "Bobbie", "Blossom", "Brianna", "Buddy", "Byron", "Caesar", "Caleb", "Celicia", "Chalmer", "Chandra", "Cindi", "Clarence", "Codie", "Corey", "Cyrus"];
var textBox = $("#txtName");
textBox.autocomplete({
    minLength: 2,
    source: function(request, response){
        var filteredNames = _.take(_.filter(names, function(name){
            return name.toLowerCase().indexOf(request.term.toLowerCase()) != -1;
        }), textBox.data("count"));
        response(filteredNames);
    }
});

You can play with the sample on jsfiddle.


Happy coding!

3 comments:

  1. i want to display a number in text box using autocomplete using j query... will u please help me

    ReplyDelete
    Replies
    1. Sorry for the delay in responding. I am totally packed up these days, so don't have enough time to help you. Try posting your question on stackoverflow and I am sure that you will get an answer.

      Delete

Note: only a member of this blog may post a comment.