Pass a parameter into Bloodhound from Typeahead?

本小妞迷上赌 提交于 2019-12-21 12:32:46

问题


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.


回答1:


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" />



回答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



来源:https://stackoverflow.com/questions/29631662/pass-a-parameter-into-bloodhound-from-typeahead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!