Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

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..." /><br />

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"];<br />var textBox = $("#txtName");<br />textBox.autocomplete({<br />    minLength: 2,<br />    source: function(request, response){<br />        var filteredNames = _.take(_.filter(names, function(name){<br />            return name.toLowerCase().indexOf(request.term.toLowerCase()) != -1;<br />        }), textBox.data("count"));<br />        response(filteredNames);<br />    }<br />});<br />

You can play with the sample on jsfiddle.

Happy coding!

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}