jqueryjquery-autocomplete

jquery autocomplete with category selection


I am using jquery automplete with category option, everything is working fine.Now i want to make categories select-able.I have gone through many things but nothing is working.Is there any way to make category selectable not label.

My code is as below:

$.widget("custom.catcomplete", $.ui.autocomplete, {

    _renderMenu: function (ul, items) {
        var self = this;
        var currentCategory = "";
        $.each(items, function (index, item) {
            if (item.category != currentCategory) {
                ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
                currentCategory = item.category;
            }
            self._renderItem(ul, item);
        });
    },

});

$('#city').catcomplete({
    delay:0,
    source : function(request, response) {
        $.ajax({
            url : '${createLink(controller:"city", action:"ajaxData")}',
            data : {
                term : request.term
            },
            dataType : "json",
            success : function(data) {
                if (data.length > 0) {
                    response( $.map( data, function( item ) {
                        return {
                            label: item.label,
                            value: item.category,
                            category: item.category,
                        }
                    }));   
                }
                else{ 
                    response([{ category: 'No results found', val: "",label:""}]);
                }
            }
        });
    },  
    focus: function(event, ui) {
        $("#city").val(ui.item.category);
        return false;
    }   ,
    select: function( event, ui ) {
        window.location.href = ui.item.category;
    },      
}); 

Solution

  • This will solve your problem, but may not be the best solution.

    What I have done

    Live Demo @ JSFiddle:

    http://jsfiddle.net/dreamweiver/bp0x1yc4/11/

    JS Code :

    $(document).on('click', '.ui-autocomplete-category', function () {
        $("#search").val($(this).html());
        $("#search").catcomplete("close");
        selectHandler($(this).html());
    });
    
    var selectHandler = function (data) {
        //process selected data
        console.log("selected value: " + data);
    };