Typeahead

answer to stackoverflow.com question

by marson parulian

HTML

<input id="typeahead" type="text" />
<ul id="list"></ul>

CSS

.highlight {
	font-weight: bold;
	text-decoration: underline;
	font-style: italic;
}

JavaScript

$(document).ready(function() {
        // Init variable to save last ajax request.
        var xhr = null;
		$('#typeahead').on({
			input: function() {
				$('#list li').remove();
                // Abort previous ajax request, if any.
                if(xhr !== null){
                 	xhr.abort();
                    xhr = null;
                }
				xhr = $.ajax({
					url: 'http://smpl-php.com/jquery/test/northwind.php',
                    method: 'post',
					data: { 'name': $('#typeahead').val() },
					dataType: 'json',
					success: function(response) {
						$(response).each(function(i, e) {
							q = $('#typeahead').val();
                            //Find substring,encapsulate the substring with span.highlight.
                            var match = e.name.replace(new RegExp(q,"i"), function(m){
                                return "<span class='highlight'>"+m+"</span>"});
							$('#list').append('<li class="employeeID-'+ e.id +'">'+ match +'</li>');
						});
					},
					error: function(error) {}
				});
			}
		});
	});