5

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.

1 Answer 1

5

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 );
};
Sign up to request clarification or add additional context in comments.

1 Comment

Here's an update: the example in the API is currently found at jqueryui.com/autocomplete/#custom-data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.