Get Off My Lawn
Get Off My Lawn

Reputation: 36351

jQuery Autocomplete not showing values

I can not seem to get this autocomplete working. I am using this for my search field:

<input type="text" data-cat="1" class="form-control interest-search" placeholder="Find some interests">

I am then making an ajax request to my server to search the database for similar items like this:

var search = null;
$(document).on('keyup', '.interest-search', function(){
    clearTimeout(search);
    var $this = $(this);
    search = setTimeout(function(){
        var search = $this.val();
        var category = $this.attr('data-cat');
        $.post('/suggest/interest', JSON.stringify({interest: search, category: category}), function(data){
            $('input[data-cat=' + category + ']').autocomplete({
                source: data
            });
        }, 'json');
    }, 200);
});

I then get a json array of results back that look like this:

[
    {"label":"biking","value":"2","total":"1"},
    {"label":"billiards","value":"3","total":"3"}
]

But what happens, is nothing displays. I have no errors either.

Here is a fiddle: http://jsfiddle.net/s7zakqzo/

Upvotes: 0

Views: 30

Answers (1)

Ben Aubin
Ben Aubin

Reputation: 5667

var search = null;

var data = [
    {label:"biking",value:"2",total:"1"},
    {label:"billiards",value:"3",total:"3"}
];

$(document).on('keyup', '.interest-search', function(){
    clearTimeout(search);
    var $this = $(this);
    search = setTimeout(function(){
        var search = $this.val();
        $this.autocomplete({
            source: data
        });
    }, 200);
});

Change $('input[data-cat=' + category + ']') to $this. It fixes the problem.

Upvotes: 1

Related Questions