我正在处理自动填充表单字段,并且在格式化我希望传递给它的JSON时遇到一些麻烦。我使用ID字段进行自动完成,但JSON返回如下:
{"users":["12345","23456","34567", ... ]}
据我了解,我需要一系列数据用于JQuery的自动完成 - 我正在使用它 - 尽管我似乎无法摆脱围绕此问题的哈希。有什么建议?或者如果我在其他地方出错,指导会很棒!
以下是其他相关代码:
JS
$(document).on('ready page:load', function(){
$( "#user_****Id" ).autocomplete({
source: $('#user_****Id').data('autocomplete-source')
})
})
表格(haml)
= simple_form_for [:admins, @user] do |f|
...
= f.input :****Id, input_html: { data: { autocomplete_source: new_admins_user_path } }
...
控制器
def new
@hospitals = Hospital.all
@hospitals_autocomplete = @hospitals.map(&:id)
respond_to do |format|
format.html
format.json {render json: @hospitals_autocomplete}
end
end
谢谢大家 - 史蒂夫。
答案 0 :(得分:0)
如果您正在寻找自动填充功能,我建议Jquery TokenInput,我自己使用它并且易于设置。我给您举个例子: -
表单字段中的
<% form_for(@user,:url=>new_user_path) do |f|%>
//other input text and text area fields
//autocomplete field to add tag to user and also show existing tags
//suppose this field is user_tag_list
<%= f.text_field :tag_list, "data-pre" => @user.tags.map(&:attributes).to_json %>
<%end%>
js代码中的: -
//activate the autocomplete text field(user_tag_list) and call ajax to return json from the controller
$("#user_tag_list").tokenInput("/users/show_user_tags.json", {
crossDomain: false,
placeholder: "Add your Favorite user tags",
prePopulate: $("#user_tag_list").data("pre"),
theme: "facebook",
hintText: "Tag this user with your fav tags",
noResultsText: "Well,search for you fav tags",
searchingText: "here it comes <i class='fa fa-spinner fa-spin fa-lg'></i>",
tokenLimit:3,
//add title to search on basis of title on form submit
tokenValue: 'name',
resultsLimit:10,
resultsFormatter: function(item){ return "<li><p><span style='font-size:1em !important;'><b>" + item.name + "</b></span></p></li>" },
tokenFormatter: function(item) { return "<li><p>" + item.name + "</p></li>" },
preventDuplicates: true
});
控制器代码...在用户控制器中调用show_user_tags
def show_user_tags
@tags = UserTag.where("title like ?", "#{params[:q].capitalize}%")
@tags = @tags.map do |c|
{ :id => c.id,:name => c.title}
end
respond_to do |format|
format.html
format.json { render :json => @tags }
end
end