【发布时间】:2014-03-17 10:36:55
【问题描述】:
我认为有这个循环:
<% @item.inventory_items.each do |p| %>
我在上面的do 块中为每个inventory_item 循环了这个表单:
<%= form_for(@list_item) do |f| %>
<%= f.hidden_field :upc, :value => @item.upc %>
<%= f.hidden_field :inventory_item_id, :value => p.id %>
<%= f.select :shopping_list_id, options_for_select(ShoppingList.options_for_list(current_user.shopping_lists)), {}, :class => "form-control" %>
<%= f.submit("Add It!", class: "btn btn-add") %>
<% end %>
我现在已将此表单放入 Bootstrap 3 模式中。为简洁起见,我不会发布整个模式。这是触发器,它为每个inventory_item 循环:
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#formModal">Add To List</button>
我遇到的问题是我的表单使用来自循环的inventory_items 的属性来填充此表单中的隐藏字段之一。所以这是我的问题:
当它被触发时,如何将这个变量从循环传递到模态?
编辑
这是我目前的模式:
<div class="modal fade" id="addListItem" tableindex="-1" role="dialog" aria-labelledby="addListItem" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="form-label">Add this item to a shopping list.</h4>
</div>
<div class="modal-body">
<%= form_for(@list_item) do |f| %>
<%= f.hidden_field :upc, :value => @item.upc %>
<%= f.hidden_field :inventory_item_id, :id => "inventory-item-id" %>
<%= f.select :shopping_list_id, options_for_select(ShoppingList.options_for_list(current_user.shopping_lists)), {}, :class => "form-control" %>
<%= f.submit("Add It!", class: "btn btn-add") %>
<% end %>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
来自@David Antaramian 的自定义 .js:
$('button,[data-inventory-item-id]').click(function() {
var inventoryID = $(this).data('inventory-item-id');
$('#inventoryID').prop('value', inventoryID);
$('#addListItem').modal('show');
});
【问题讨论】:
-
我不明白你代码中的循环。我假设您正在尝试做的是使用您创建的“添加到列表”按钮来激活包含单个
inventory_item表单的模式,此时用户可以选择哪个ShoppingList来保存该项目。我想掌握的是:form_for循环是@item-do-p循环的子语句吗?还是分开的?每种形式是否有单独的模态,还是全部定义在一个大模态中? -
对不起,我应该澄清一下。
form_for是@item-do-p循环的子语句。我只有一个模式,我希望它可以从循环中填充正确的隐藏字段属性,这取决于选择了哪个inventory_item按钮。你对我最终目标的假设是正确的。这样就清楚了吗? -
编辑了我的问题以澄清。
-
是的,这一切都清楚了。我正在尝试仅使用单个模态对话框来完成此操作的方法。
-
我认为这些 SO 线程很相似,应该对您有所帮助:stackoverflow.com/a/20724640/1422070 和 stackoverflow.com/a/10635652/1422070
标签: javascript ruby-on-rails forms twitter-bootstrap