gpt4 book ai didi

javascript - 如何使用自定义参数让预先输入填充我的搜索栏?

转载 作者:行者123 更新时间:2023-12-02 16:16:25 25 4
gpt4 key购买 nike

我在我的应用程序中安装了“twitter-typeahead-rails”并进行了设置,以便当我开始在搜索框中输入内容时,建议会下降。然后,当我单击建议时,搜索框就会被填充。但现在,它会被 displayKey 填充,如定义建议的 html 中所示:

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

如何让它仅使用 user.name 填充搜索栏?

Gemfile

gem 'twitter-typeahead-rails'

预先输入的搜索框

<%= 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'

users__controller.rb

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

最佳答案

可以按照 docs here 添加自定义建议,如下所示

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

这些是呈现的下拉菜单项。 displayKey 是从下拉列表中选择某项后在文本框中呈现的键。

displayKey 可以这样渲染

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

这是一个simple demo

希望这有帮助。

关于javascript - 如何使用自定义参数让预先输入填充我的搜索栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29527762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com