gpt4 book ai didi

javascript - Rails 3 个不同的自动完成字段

转载 作者:行者123 更新时间:2023-12-02 19:18:51 31 4
gpt4 key购买 nike

我在页面上有 2 个不同的自动完成字段,每个字段都从数据库中的不同源填充。我的问题是,当我测试页面时,两种自动完成行为有时会在彼此的文本字段中切换。

我的 View 部分如下所示(我遵循 railscasts ):

<fieldset>
<%= f.text_field :ability_title, {:class => 'autocomplete_field', data: { autocomplete_source: abilities_path } } %>
<%= f.label :points %>: <%= f.text_field :points %>
<%= f.hidden_field :_destroy %>
<%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>

<fieldset>
<%= f.text_field :mission_title, {:class => 'autocomplete_field', data: {autocomplete_source: missions_path } } %>
<%= f.hidden_field :_destroy %>
<%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>

我的 JavaScript:

jQuery ->
$('fieldset').live 'click', ->
$('.autocomplete_field').autocomplete
source: $('.autocomplete_field').data('autocomplete-source')

和我的 Controller :

def index
if params[:term].present?
@abilities = Ability.search_titles(params[:term])
else
@abilities = Ability.all
end

respond_to do |format|
format.html # index.html.erb
format.json { render json: @abilities }
end
end

def index
if params[:term].present?
@missions = Mission.search_titles(params[:term])
else
@missions = Mission.all
end

respond_to do |format|
format.html # index.html.erb
format.json { render json: @missions.map(&:title) }
end
end

谢谢

最佳答案

我认为你只需要通过 id 来区分两个文本字段,例如:

<fieldset>
<%= f.text_field :ability_title, {:id => 'autocomplete_field1', data: { autocomplete_source: abilities_path } } %>
<%= f.label :points %>: <%= f.text_field :points %>
<%= f.hidden_field :_destroy %>
<%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>

<fieldset>
<%= f.text_field :mission_title, {:id => 'autocomplete_field2', data: {autocomplete_source: missions_path } } %>
<%= f.hidden_field :_destroy %>
<%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>
My javascript:

jQuery ->
$('fieldset').live 'click', ->

$('#autocomplete_field1').autocomplete
source: $('#autocomplete_field1').data('autocomplete-source')
$('#autocomplete_field2').autocomplete
source: $('#autocomplete_field2').data('autocomplete-source')

编辑:更优雅的解决方案:

jQuery ->
$('fieldset').live 'click', ->
$('#autocomplete_field1, #autocomplete_field2').each (index, element) =>
$(element).autocomplete
source: $(element).data('autocomplete-source')

关于javascript - Rails 3 个不同的自动完成字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12778097/

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