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

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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!

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}