Rails Jquery 从表中选定的复选框计算总数 [英] Rails Jquery compute total from selected checkboxes in a table

查看:38
本文介绍了Rails Jquery 从表中选定的复选框计算总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我的 rails 视图,它有一个表单,可以拉出 product_items 并让用户检查他们想要购买的所有项目并在表格下方显示总订单金额.(附图)

我的代码如下所示.服务器端很好(我可以在其中保存订单)但我需要客户端 js 的一些帮助来计算订单总额并在表格下方显示订单总额.

 <% @cause.product.product_items.each 做 |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>数量</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></选择><i></i></td><td><b><big><%= number_to_currency(item.price, precision: 0) %></big></b></td></tr><%结束%></tbody>

<label><strong>总订单金额:</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()));}});

解决方案

为了计算总金额,您必须观察是否有被选中/未选中的产品和产品数量的变化也会改变.

您可以将视图更新为如下所示(为了简单起见,省略了这些内容):

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

如您所见,我使用了tag helper 来创建一个名为 price 的 HTML5 数据属性.我这样做是为了以后更容易获得产品价值.

现在,由于您的视图已就位,您所要做的就是在每次选中/取消选中产品复选框或产品数量发生变化时计算迭代项目列表.你可以有这样的东西:

//这一行将向您的输入和选择添加事件侦听器//在#products-items 表下$('#product-items input[type=checkbox], #product-items select').change(function(e) {//初始化变量var totalAmount = 0;//我们只需要选中复选框的行var $tableRows = $('#product-items tr').has('input[type=checkbox]:checked');//遍历每一行以获得所有需要的信息$.each($tableRows, function(i, row) {var $row = $(row);//获取当前产品的数量var 数量 = row.find('select').val();//如果数量设置为 0,您可以取消选中产品//为了更好的用户体验如果(数量 === 0){$row.find('input').prop('checked', false);} 别的 {//从 data-price 属性中获取产品价格var price = $row.data('price');//我正在将价格转换为整数,但您可以//改变它并使用 parseFloat 如果你想totalAmount += parseInt(price) * parseInt(quantity);}});$('#total-amount').text('$' + totalAmount);});

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

So here is my rails view which has a form which pulls the product_items and lets the user check all the items they want to buy and display the total order amount underneath the table. (attached pic)

My code looks like below. The server side is good (where I can save the order) but I need some help on the client side js to compute the order total and displaying the order total underneath the table.

    <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>

Here is some js, I wanted to identify the checkbox which is checked and grab the qty in that table row (again not sure how to do this)

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

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

解决方案

In order to calculate the total amount, you will have to watch for changes for products that get selected/unselected and products quantity that gets changed as well.

You could update your view to look like this (things were left out for the sake of simplicity):

<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>

As you noticed, I used the tag helper in order to create an HTML5 data attribute with the name price. I did that in order to make it easier to get the product value later on.

Now, since you have your view in place, all you have to do is calculate iterate through the item list every time a product checkbox gets checked/unchecked or a product's quantity changes. You could have something like this:

// 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);
});

This way every time you change the quantity or check/uncheck a product, the total amount will be calculated from the beginning.

这篇关于Rails Jquery 从表中选定的复选框计算总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆