Pass a parameter into Bloodhound from Typeahead?
Asked Answered
S

2

7

I am setting up a form with Typeahead. I have two input fields next to each other, and I need an autocomplete on each of them. My HTML looks like this:

<select id="numerator">
    <option value="presentation">presentation</option>
    <option value="chemical">chemical</option>
</select>
<input id="numeratorId" class="typeahead" type="text" />
<br/>
<select id="denominator">
    <option value="presentation">presentation</option>
    <option value="chemical">chemical</option>
</select>
<input id="denominatorId" class="typeahead" type="text" />

Each of the input fields will autocomplete by looking at an API endpoint. This should be of the form /api/1.0/code?type=presentation&code=123 or /api/1.0/code?type=chemical&code=123.

The value of the type parameter in the API call should depend on the value of the <select> element next to each input field.

The problem that I'm having is that I don't know how to tell Bloodhound what the type parameter should be.

Ideally I'd like to pass it in to Bloodhound, but I don't know how to do that. This is my JavaScript:

var bnfMatches = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: {
      url: '/api/1.0/code?',
      replace: function(url, uriEncodedQuery) {
        url = url + 'code=' + uriEncodedQuery;
        // How to change this to denominator for denominator queries?
        val = $('#numerator').val(); 
        if (!val) return url;
        return url + '&code_type=' + encodeURIComponent(val)
      }
  }
});

$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 2
},
{
    name: 'states',
    displayKey: 'id',
    source: bnfMatches.ttAdapter()
});

I'd be very grateful for any suggestions.

Snodgrass answered 14/4, 2015 at 15:39 Comment(3)
Appear both input elements have same id ? numeratorId ?Suffuse
Sorry, that's a mistake. Fixed.Snodgrass
See post. Adjusted id's of input elements, added bnfMatches.initialize() , selected select element having id beginning with focused input element id.Suffuse
S
5

Try

html

Note, removed duplicate id numeratorId at input elements; substituted numeratorId , denominatorId , respectively. This also permits selecting select element within replace function.

<select id="numerator">
    <option value="presentation">presentation</option>
    <option value="chemical">chemical</option>
</select>
<input id="numeratorId" class="typeahead" type="text" />
<br/>
<select id="denominator">
    <option value="presentation">presentation</option>
    <option value="chemical">chemical</option>
</select>
<input id="denominatorId" class="typeahead" type="text" />

js

Note, bnfMatches not appear initialized. Added bnfMatches.initialize(); after Bloodhound settings.

var bnfMatches = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      remote: {
          url: '/api/1.0/code?',
          replace: function(url, uriEncodedQuery) {
            var val = $(".typeahead").filter(":focus")
                     .attr("id").slice(0, -2);
            var res = (url + "type=" + $("#" + val).val() + "&code=" 
                      + encodeURIComponent(uriEncodedQuery));
            console.log(res);
            return res
          }
      }
    });

    bnfMatches.initialize();

    $('.typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 2
    },
    {
        name: 'states',
        displayKey: 'id',
        source: bnfMatches.ttAdapter()
    });

var bnfMatches = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: {
      url: '/api/1.0/code?',
      replace: function(url, uriEncodedQuery) {
        var val = $(".typeahead").filter(":focus")
                 .attr("id").slice(0, -2);
        var res = (url 
                  + "type=" + $("#" + val).val() + "&code=" 
                  + encodeURIComponent(uriEncodedQuery));
        console.log(res);
        return res
      }
  }
});

bnfMatches.initialize();

$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 2
},
{
    name: 'states',
    displayKey: 'id',
    source: bnfMatches.ttAdapter()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>

<select id="numerator">
    <option value="presentation">presentation</option>
    <option value="chemical">chemical</option>
</select>
<input id="numeratorId" class="typeahead" type="text" />
<br/>
<select id="denominator">
    <option value="presentation">presentation</option>
    <option value="chemical">chemical</option>
</select>
<input id="denominatorId" class="typeahead" type="text" />
Suffuse answered 14/4, 2015 at 16:54 Comment(3)
Thanks. This is one way of doing it, and it works. It would be nicer to pass a value in if possible, but if it's not possible, then it's not possible!Snodgrass
You are welcome:) Not certain interpret "It would be nicer to pass a value in if possible," correctly ? replace function not implement desired pattern ?, return expected results ?Suffuse
I just mean that the value of the second parameter in the replace function is tied to a specific element in the DOM with a specific ID. This is something we generally try to avoid in JS, because tying bits of the JS directly to the HTML makes things fragile.Snodgrass
P
2

Bloodhound's replace can be used like this

replace: function (url, query) {
   if(_el.val() === "users"){
     return url + '/users?q=' + query;
   }else{
     return url + '/repositories?q=' + query;
   }
}

Here is the full example. In the example, I used github's public api. The select dropdown is used to switch between users and repositories.

var make_dataset = function (el) {
    var _el = el; // nearest select for input
    var bloodhound = new Bloodhound({
        datumTokenizer: function (datum) {
            return Bloodhound.tokenizers.whitespace(datum.value);
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: 'https://api.github.com/search',
            filter: function (users) {
                return $.map(users.items, function (user) {
                    return {
                        value: user.url
                    };
                });
            },
            replace: function (url, query) {
                if (_el.val() === "users") {
                    return url + '/users?q=' + query;
                } else {
                    return url + '/repositories?q=' + query;
                }
            }
        }
    });
    bloodhound.initialize();

    var dataset = {
        source: bloodhound.ttAdapter(),
    }

    return dataset;
}

/* initial setup */
$('.typeahead').each(function () { // each input
    var select = $(this).siblings('select'); // select near each input
    $(this).typeahead({
        hint: true,
        highlight: true,
        minLength: 2
    }, make_dataset(select)); // make_dataset initializes a bloodhound instance
});

Here is a full DEMO

Hope this helps

Procurance answered 15/4, 2015 at 2:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.