Share Knowledge
Share Knowledge

Reputation: 297

jQuery autocomplete UI - doesn't work

I am trying to make an autocomplete widget that will display item's codes returned from a database.

I have successfully made it so my database will return the appropriate JSON response.

The problem now is I don't know why the drop-down list doesn't show up.

Here's the code down below:

<input type="text" id="search" class="form-control" placeholder="">

<form action="post" action="" id="spareParts" class="spareparts">

</form>

$('#search').keyup(function(event) {
        var search = $(this).val();

        if($.trim(search).length){
            var arr = [];
            $.ajax({
                url: 'get_spareparts',
                type: 'POST',
                dataType: 'JSON',
                data: {item: search},
                success: function (data) {
                    arr = $.parseJSON( data );

                    console.log(arr);// CONSOLE.LOG WORKS WELL
                    //[Object { id="1", value="25.00", desc="Fuel pump", more...}]

                   // AUTOCOMPLETE DOESN'T WORK
                    $('#spareParts').autocomplete({
                        minLength:0,
                        source: arr
                    });
                }
            });
    } 
});

Upvotes: 1

Views: 81

Answers (1)

dfsq
dfsq

Reputation: 193261

The autocomplete with AJAX loaded data should be configured differently. source property can be a function which accepts a callback parameter. You should feed this callback with data loaded from server.

Also you don't need to bind keyup event manually. Your code will become:

$('#search').autocomplete({
    minLength: 0,
    source: function(request, response) {
        $.ajax({
            url: 'get_spareparts',
            type: 'POST',
            dataType: 'JSON',
            data: {item: request.term}
        }).done(function(data) {
            response(data.map(function(el) {
                return {
                    value: el.value, 
                    label: el.desc
                };
            }))
        });
    }
});

Upvotes: 3

Related Questions