Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap 3 typeahead.js - remote url attributes

I'm trying to call my remote url with added attributes to the url.

For now I have this working:

$('#league').typeahead({
        remote: '/typeahead/get_league?query=%QUERY',
        limit: 10
});

Now I would like to do something like this:

$('#league').typeahead({
        remote: function () {
            var q = '/typeahead/get_league?query=%QUERY';
            if ($('#sport').val())
                q += "&sport=" + encodeURIComponent($('#sport').val());
            return base_url + q;
        },
        limit: 10
});

I would like to add the GET attribute 'sport' to the URL so I can narrow down my query on the backend. I tried the code above but I get a JS error.

The previous version of Bootstrap Typeahead allowed this type of setup. It was very useful as I could update the remote URL every time a key get hit.

Any idea how to make that work for this version ?

like image 977
koxon Avatar asked Aug 08 '13 03:08

koxon


2 Answers

remote is exclusively for typeahead.js (not part of Bootstrap). But you are not using the remote correctly, it can be either a string or an object, not a function.

When you need to change the request URL, you can use replace:

$('#league').typeahead({
    remote: {
        url: '/typeahead/get_league?query=%QUERY',
        replace: function () {
            var q = '/typeahead/get_league?query=%QUERY';
            if ($('#sport').val()) {
                q += "&sport=" + encodeURIComponent($('#sport').val());
            }
            return base_url + q;
        }
    },
    limit: 10
 });

Check the docs here

Hope it helps.

like image 188
Hieu Nguyen Avatar answered Sep 22 '22 16:09

Hieu Nguyen


Hieu Nguyen solution will not work for %QUERY wildcards. According to Bloodhound.js documentation,

replace – .... If set, no wildcard substitution will be performed on url.

Bloodhound docs on github

So %QUERY will be passed as string without being replaced by text entered from user.

So you should put typeahead value into your url :

$('#league').typeahead({
remote: {
    url: '/typeahead/get_league?query=%QUERY',
    replace: function () {
        var q = '/typeahead/get_league?query=' + $('#league').val();
        if ($('#sport').val()) {
            q += "&sport=" + encodeURIComponent($('#sport').val());
        }
        return base_url + q;
    }
},
limit: 10

});

like image 44
aKiRa Avatar answered Sep 21 '22 16:09

aKiRa