Rails Jquery从表中的选定复选框计算总计

时间:2016-04-18 20:56:55

标签: jquery ruby-on-rails ruby

所以这是我的rails视图,它有一个拉动product_items的表单,让用户检查他们想要购买的所有商品,并在表格下方显示总订单金额。 (附图) this is the screenshot of the view

我的代码如下所示。服务器端很好(我可以保存订单),但我需要在客户端js上帮助计算订单总数并在表格下方显示订单总数。

    <tbody>
    <% @cause.product.product_items.each do |item|  %>
    <tr>
      <td width="60%"><label class="checkbox"><%= f.check_box(:items, { multiple:true, class: 'item_checkbox' }, item.id, nil) %><i></i><%= item.title %></label></td>

      <td>
        <label class="select">
        <select name="items[<%= item.id %>][qty]">
        <option value="0" selected disabled>Qty</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>

        </select>
        <i></i>
        </label>
      </td>
      <td><b><big><%= number_to_currency(item.price, precision: 0) %></big></b></td>
    </tr>
    <% end %>

</tbody>
</table>
</div>
<label><strong>Total order amount: </strong><span class="lead" id="order_amount"></span></label>

这是一些js,我想确定选中的复选框并抓取该表行中的数量(再次不确定如何执行此操作)

$(".item_checkbox").change(function() {
  if ($(this).is(":checked")) {

   alert($(this).siblings($('#select option:selected').text()));
  }
});

2 个答案:

答案 0 :(得分:2)

为了计算总金额,您必须观察以获取被选中/未被选中的产品的更改以及更改的产品数量。

您可以将视图更新为这样(为简单起见,事情被遗漏了):

<table id="product-items">
  <tbody>
    <% @cause.product.product_items.each do |item|  %>
      <%= tag :tr, data: { price: item.price } do %>
        <td>
          <label class="checkbox">
           <%= f.check_box(:items, class: 'item_checkbox', item.id) %>
           <%= item.title %>
          </label>
        </td>
        <td>
          <label class="select">
          <select>...</select>
        </td>
        <td>
          <%= number_to_currency(item.price, precision: 0) %>
        </td>
      <% end %>
    <% end %>
  </tbody>
</table>
<div id='total-amount'></div>

正如您所注意到的,我使用了tag帮助程序来创建名为price的HTML5数据属性。我这样做是为了让以后更容易获得产品价值。

现在,既然您已经有了自己的观点,那么每次检查/取消选中产品复选框或产品数量发生变化时,您所要做的就是计算项目列表的迭代次数。你可以这样:

// This line will add event listeners both to your inputs and selects
// under the #products-items table
$('#product-items input[type=checkbox], #product-items select').change(function(e) {

  // Initialize vars
  var totalAmount = 0;

  // We need only rows that have checked checkboxes
  var $tableRows = $('#product-items tr').has('input[type=checkbox]:checked');

  // Iterate through each row in order get all needed info
  $.each($tableRows, function(i, row) {
    var $row = $(row);

    // Get the quantity for current product
    var quantity = row.find('select').val();

    // You could uncheck the product if quantity is set to 0
    // for better user experience
    if (quantity === 0) {
      $row.find('input').prop('checked', false);
    } else {
      // Get the product price from the data-price attribute
      var price = $row.data('price');

      // I am converting the price to an integer, but you could
      // change that and use parseFloat if you want to
      totalAmount += parseInt(price) * parseInt(quantity);
    }
  });

  $('#total-amount').text('$' + totalAmount);
});

这样,每次更改数量或选中/取消选中产品时,总金额将从头开始计算。

答案 1 :(得分:0)

感谢@ioannis提供的帮助,这是我的最终答案,解决了我的问题。这也显示订单摘要。

$('#product-items input[type=checkbox], #product-items select').change(function(e) {

  // Initialize vars
  var totalAmount = 0;
  var totalItemAmount = 0;
  $('#order_summary').text('');
  // We need only rows that have checked checkboxes

  $("input:checkbox:not(:checked)")

  var $tableRowsNotChecked = $('#product-items tr').has('input[type=checkbox]:not(checked)');

  $.each($tableRowsNotChecked, function(i, row) {
    var $row1 = $(row);
    $row1.find('.item_qty').hide();

  });

  var $tableRows = $('#product-items tr').has('input[type=checkbox]:checked');

  // Iterate through each row in order get all needed info
  $.each($tableRows, function(i, row) {

    // Get the quantity for current product
    var $row = $(row);
    var qty = $row.find('select').val();
    $row.find('.item_qty').show();

    // You could uncheck the product if quantity is set to 0
    // for better user experience
    if (qty === 0) {
      $row.find('input').prop('checked', false);
    } else {
      // Get the product price from the data-price attribute
      var price = $row.data("price");
      var item = $row.data("item-name");

      // I am converting the price to an integer, but you could
      // change that and use parseFloat if you want to
      totalItemAmount = parseInt(price) * parseInt(qty);
      totalAmount += totalItemAmount;
      $('#order_summary').append( "<tr><td>" + item + "</td><td>" + qty + "</td><td>$" + parseInt(totalItemAmount) + "</td></tr>");
    }
  });
  $('#order_summary').append( "<tr><td></td><td><strong>Total Amount:</td><td>$" + totalAmount + "</td></strong></tr>");
  $('#order-amount').text(totalAmount);
  $('#cause_amount').val(totalAmount);
  $( "#cause_amount" ).trigger( "change" );
  // $('input.submit_contribution').val('Buy Now');
});