Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AutoComplete, custom return data

I'm trying to create an auto-complete box and have been having problems due to returning custom data, I cannot seem to get it to populate the autocomplete box.

This is the data (JSON):

[{"user_id":"1","user_name":"jarru"},{"user_id":"2","user_name":"harryq"},{"user_id":"3","user_name":"sleet"}]

And this is the javascript I'm using:

<script type="application/javascript">
$(document).ready(function(){
    $("#add_email_user").autocomplete({
            source: baseurl+"users/ajax/users/",
                        dataType: 'json',
                        success: function(data) {
                        console.log("asd");
                          response($.map(data, function(item) {
                            return {
                              label: item.user_name,
                              value: item.user_id
                            }
                          }));
                          }
        });

});
</script>

When I use this code, nothing happens, there is about a 3px dropdown with nothing in it. The data is being requested properly (as reported by FireBug console) but nothing is populated into the dropdown.

like image 578
Prisoner Avatar asked Jul 11 '11 14:07

Prisoner


1 Answers

What you need to do is provide your own _renderItem function. This example in the API shows you how to do just that. You can also take a look at the source code of the plugin to see how it's done normally.

$( "#project" ).autocomplete({
    minLength: 0,
    source: projects,
    focus: function( event, ui ) {
        $( "#project" ).val( ui.item.label );
        return false;
    },
    select: function( event, ui ) {
        $( "#project" ).val( ui.item.label );
        $( "#project-id" ).val( ui.item.value );
        $( "#project-description" ).html( ui.item.desc );
        $( "#project-icon" ).attr( "src", "images/" + ui.item.icon );

        return false;
    }
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
        .appendTo( ul );
};
like image 196
Radu Avatar answered Nov 05 '22 10:11

Radu