Friday, May 10, 2013

jQuery Autocomplete with image


Recently, we were working on requirement where we need a search result like "facebook friend search" which returns in following format:















To get it working, we used jQuery's Autocomplete feature. Three steps to implement same.

1. A Text box.

2. You need data to display. If you are searching using a service, you can  call using Ajax that returns a set of results and bind it.

3. Display in following a way is tricky :)  i'll explain in detail as given below.


Lets start :

Step 1. Create a Text-box as follows:

<body>
  <input id="friends" />
</body>

Step 2. Call service using Ajax and prepare data-set to bind.


  $("#friends").autocomplete({
                source: function (request, response) {

                    $.ajax({

                        url: '<Service Url>',
                        type: "GET",
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data.Data, function (item) {
                                return {
                                    Name: item.Name,
                                    ImageUrl: item.ImageUrl
                                }
                            }));
                        }
                    });
                },
                minLength: 2,
                select: function (event, ui) {
                    log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
                },
                open: function () {
                    $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
                },
                close: function () {
                    $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
                }
            });

Notesource method is populated with results returned by service call. We have name and image url  there. It creates a a list of data as needed.

We can also assign some static data if needed like:


$(function() {
    var availableTags = [
      "x",
      "y",
      "y",
      "z"
    ];
    $( "#friends" ).autocomplete({
      source: availableTags
    });


Step 3: Create result like Facebook i.e. Image with text.

jQuery's data attribute and renderItem function finish that job for us.it can be used to create custom html in response flowing out as a result. We can apply required CSS as needed.


 $("#friends").autocomplete({
                source: function (request, response) {

                    $.ajax({
                        url: '<Service Url>',
                        type: "GET",
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data.Data, function (item) {
                                return {
                                    Name: item.Name,
                                    ImageUrl: item.ImageUrl
                                }
                            }));
                        }
                    });
                },
                minLength: 2,
                select: function (event, ui) {
                    log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
                },
                open: function () {
                    $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
                },
                close: function () {
                    $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
                }
            }).data( "autocomplete" )._renderItem = function( ul, item ) {
        var inner_html = '<a><div class="list_item_container"><div class="image"><img src="' + item.ImageUrl + '"></div><div class="label">' + item.Name + '</div></div></a>';
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append(inner_html)
            .appendTo( ul );
    };
});


Thats it! Task done.. Thanks to jQuery and its power.. simply awesome.