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 to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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!

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}