将参数传递给Typeahead的Bloodhound?

时间:2015-04-14 15:39:29

标签: javascript typeahead.js bloodhound

我正在使用Typeahead设置表单。我有两个输入字段彼此相邻,我需要在每个字段上自动完成。我的HTML看起来像这样:

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

每个input字段都会通过查看API端点自动完成。其格式应为/api/1.0/code?type=presentation&code=123/api/1.0/code?type=chemical&code=123

API调用中type参数的值应取决于每个输入字段旁边的<select>元素的值。

我遇到的问题是我不知道如何告诉Bloodhound type参数应该是什么。

理想情况下,我想把它传递给Bloodhound,但我不知道该怎么做。 这是我的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()
});

我非常感谢任何建议。

2 个答案:

答案 0 :(得分:5)

尝试

HTML

注意,在id元素处删除了重复的numeratorId input;分别替换numeratorIddenominatorId。这也允许在select函数中选择replace元素。

<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

注意,bnfMatches似乎未初始化。在bnfMatches.initialize();设置后添加了Bloodhound

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()
    });

&#13;
&#13;
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()
});
&#13;
<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" />
&#13;
&#13;
&#13;

答案 1 :(得分:2)

Bloodhound的replace可以像这样使用

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

以下是完整的示例。在这个例子中,我使用了github的public api。选择下拉列表用于在用户和存储库之间切换。

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
});

这是一个完整的 DEMO

希望这有帮助