Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeahead bootstrap3: how to pass a parameter into remote?

I am trying to use typeahed twitter for bootstrap https://github.com/twitter/typeahead.js

I need to change the remote dynamically according to what user types in and ANOTHER parameter. (The goal is to retrieve the cities of a country)

trying with country="en"; does not affect it trying with autocompleter.remote=".."; does not work.

Any idea ?

<script>
var country="fr";
var autocompleter = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: 'ajax.php?action=getVilles&country='+country+'&ville=%QUERY'
});
 autocompleter.initialize();


$('#city').typeahead(null, {
  name: 'city',
  displayKey: 'city',
  source: autocompleter.ttAdapter()
});


</script>
like image 550
yarek Avatar asked Sep 11 '14 10:09

yarek


1 Answers

This is what I've done:

var tagStudies = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('text'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: "autocomplete/study",
        replace: function(url, uriEncodedQuery) {
            study = $('#study').val();
            ssp = $("#social-security").val();

            return url + '?q=' + uriEncodedQuery + '&s=' + study + '&ssp=' + ssp 
        },
        filter: function (parsedResponse) {
            return parsedResponse.studies;
        }
    }
});

Take a look at the replace function. The first parameter is the url, and the second is what the user is typing. I made a concatenation to pass the query and 2 extra params. If you copy the code, make sure you replace 'text' for 'value' in datumTokenizer. Hope it helps

like image 149
Eduardo Pacios Avatar answered Oct 25 '22 20:10

Eduardo Pacios