0

很抱歉这个问题有点复杂。希望有人有耐心阅读本文。

我有一个嵌套模型形式,很像这个 Railscast 中的模型: http ://railscasts.com/episodes/196-nested-model-form-revised

我的模型与 Railscast 中的嵌套表单字段非常相似。有很多问题有很多答案的调查。

我正在应用一个 jQuery-UI“自动完成”元素来使所有答案表单字段成为自动完成元素。但是,因为是嵌套的表单域,所以我的文档中有很多答案域。这通常不是问题,但我需要在显示标签但提交自动完成选择的 ID 时应用此解决方案。 自动完成将值而不是标签应用于文本框

当我在上面的链接中使用解决方案时会发生什么,标签会应用于我文档中的每个“答案表单字段”,而不仅仅是我想要的那个。因为我使用的是嵌套表单,并且必须将自动完成逻辑应用于每个“答案表单字段”,所以我必须通过此选择器 '[type="text"][name*="[answer]"]' 选择它们这不是很具体,但尽我所能。

我绞尽脑汁想知道如何使用 jQuery 选择器来选择特定的答案字段而不是所有答案字段。

非常感谢您的任何帮助。

4

2 回答 2

0

假设您的Question模型是accepts_nested_attributes_for您的Answer模型,您可以按如下方式设置模板:

<%= form_for @question do |question_builder| %>
  <% @question.answers.each_with_index do |answer, i| %>
    <% question_builder.fields_for :answers, answer do |answer_builder| %>
      <%= answer_builder.text_field :content, :id => "answer-#{i}" %>
    <% end %>
  <% end %>
<% end %>

加载了与 相关联的先前保存的答案(或构建的新答案)后@question,您可以使用它来遍历带有索引的答案,i并使用唯一的 html id 为“answer-i”呈现每个答案的输入,您可以使用它从 jQuery 中唯一地识别您的答案。

希望这就是你要找的。

于 2012-10-30T06:17:19.510 回答
0
$('[type="text"][name*="[answer]"]').autocomplete
source: $('[type="text"][name*="[answer]"]').data('autocomplete-source')
select: (event, ui) ->
  event.preventDefault()
  $(this).val ui.item.label
  $(this).siblings('[name*="[hidden]"]').val ui.item.value
focus: (event, ui) ->
  event.preventDefault()
  $(this).val ui.item.label

这是我最终使用的咖啡脚本代码。感谢@cdesrosiers 的回答。我意识到我已经为每个答案文本字段获得了唯一的 ID。因此,作为我的问题的第二部分,我需要一种使用 jQuery 选择器的方法,该方法允许我将 .autocomplete jQuery 方法应用于包含名称 [answer] 的所有文本字段。

Then related to this question ( Autocomplete applying value not label to textbox ), I needed a way to select a specific answer text field since I had a form with many answer text fields. The answer was to use the jQuery selector $(this) to refer to "this" specific answer text field. Hope this helps someone else trying to learn jQuery selectors.

jQuery this selector was a helpful question in helping me figure this out.

@cdesrosiers, Can you update your answer with my addition and I can mark your response as the answer?

于 2012-10-30T23:21:48.787 回答