我在Rails应用程序中构建订单页面,并且我使用CoffeeScript和jQuery来显示在购物车中选择的产品。当我单击产品的单选按钮并选择添加到购物车时,产品名称和价格将显示在购物车中。如果再次单击“添加到购物车”,则会在新行上添加“产品”。我想改为显示产品名称:
(2)Twin Mattress $ 700
order.js.coffee
$ ->
$("input:radio").change(->
if $(this).prop("checked", true)
price = "<b>#{$(this).data('price')}</b>"
dimensions = "<b>#{$(this).data('dimensions')}</b>"
$("#product_details").html("#{price}#{dimensions}")
)
$("#add_to_cart").click((e)->
e.preventDefault()
$cart = {}
$input = $("input:radio:checked")
$label = $("label[for='#{$input.attr("id")}']")
$form = $('#new_order')
product_id = $input.val()
$hidden_input = "<input type='hidden' name='#{$input.attr('name')}' value='#{product_id}' />"
$form.prepend($hidden_input)
$("#cart").append("#{$label.text()}<br/>")
$.each($form.find("input:hidden"), (index, value) ->
$(this).attr('name', $(this).attr('name').replace(/\d+/g, index))
)
)
_form.html.erb
[<%= render partial: "error_messages", locals: { object: @order } %>
<div class="shopping-experience">
<div class="row">
<div class="col-md-4">
<ul class="product-list">
<li>
<%= f.fields_for :line_items do |ff| %>
<% products.each do |product| %>
<%= ff.label :product_id, product.name, for: "order_line_items_attributes_0_product_id_#{product.id}" do %>
<span><%= product.name %> <%= price_of(product) %></span>
<% end %>
<%= ff.radio_button :product_id, product.id, data: { price: price_of(product), dimensions: product.dimensions } %>
<% end %>
<% end %>
</li>
</ul>
</div>
<div class="col-md-4">
<div class="shopping-cart">
<div id="product_details"></div>
<p><%= link_to 'Add To Cart', '#', id: 'add_to_cart' %></p>
<div id="cart"></div>
<p><%= f.submit 'Checkout' %>
</div>
</div>
</div>
</div>][1]