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 ?
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With