如何让typeahead在我的搜索栏中填充自定义参数

How can I make typeahead fill in my searchbar with custom params?

本文关键字:填充 自定义 参数 搜索栏 我的 typeahead      更新时间:2023-09-26

我在我的应用程序中安装了"twitter typeahead rails",并对其进行了设置,这样当我开始在搜索框中键入时,建议就会下降。然后,当我点击建议时,搜索框就会被填充。但现在,它会被displayKey填充,就像在定义建议的html中一样:

<div class='typeahead-name' id='<user.name>'><user.name></div>

如何在搜索栏中只填写user.name

Gemfile

gem 'twitter-typeahead-rails'

typeahead ified searchbox

<%= form_tag users_path, :method => :get do %>
    <%= text_field_tag :search, params[:search], id:"typeahead" %>
    <%= submit_tag "Search" %>
<% end %>
<script type="text/javascript">
  // initialize bloodhound engine
  $(document).ready(function(){
    var bloodhound = new Bloodhound({
      datumTokenizer: function (d) {
        return Bloodhound.tokenizers.whitespace(d.value);
      },
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      // sends ajax request to /typeahead/%QUERY
      // where %QUERY is user input
      remote: '/typeahead/%QUERY',
    });
    bloodhound.initialize();
    // initialize typeahead widget and hook it up to bloodhound engine
    // #typeahead is just a text input
    $('#typeahead').typeahead(null, {
      displayKey: function(user) {
        return "<div class='typeahead-name' id='" + user.name + "'>" + user.name + "</div>";
      },
      source: bloodhound.ttAdapter(),
    });
  });
</script>

路线

get 'typeahead/:query' => 'users#typeahead'

用户__controller.rb

def typeahead
  q = params[:query]
  render json: User.where('name like ?, "%#{q}%")
end

根据此处的文档,可以添加如下自定义建议

templates: {
    suggestion: function (data) {
        return '<p><strong>' + data.value + '</strong> - ' + data.year + '</p>';
    }
}

这些是渲染的下拉项。displayKey是从下拉列表中选择某个内容后在文本框中呈现的内容。

displayKey可以像这个一样呈现

displayKey: function(state){
  return 'Selected is ' + state.val;
}

这是一个简单的演示

希望这能有所帮助。