如何在JQuery中获取总数

时间:2018-06-20 13:31:32

标签: javascript jquery json

我使用query创建了简单的库存控制表单。它由(产品名称,价格)组成 单击添加按钮后,它将成功添加到表格行中。我的问题是加价后我的一个结局我无法计算出最终总数。我不知道该怎么做。到目前为止我尝试过的。我写在下面。任何人都可以通过代码并给出良好的解决方案。

 <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>jQuery Add / Remove Table Rows</title>
        <style type="text/css">
            table{
                width: 100%;
                margin: 20px 0;
                border-collapse: collapse;
            }
            table, th, td{
                border: 1px solid #cdcdcd;
            }
            table th, table td{
                padding: 5px;
                text-align: left;
            }
        </style>
        <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $(".add-row").click(function(){
                    tot = 0;
                    var ProductName = $("#ProductName").val();
                    var Price = $("#Price").val();
                    var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + ProductName + "</td><td>" + Price + "</td></tr>";
                    $("table tbody").append(markup);

                        tot += parseFloat(email);


                });
                // Find and remove selected table rows
                $(".delete-row").click(function(){
                    $("table tbody").find('input[name="record"]').each(function(){
                        if($(this).is(":checked")){
                            $(this).parents("tr").remove();
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
    <form>
        <input type="text" id="ProductName" placeholder="ProductName">
        <input type="text" id="Price" placeholder="Price">
        <input type="button" class="add-row" value="Add Row">
        <label>Amount </label>
        <input type="text" size="30" height="20" id="tot" placeholder="Total">
    </form>
    <table>
        <thead>
        <tr>
            <th>Select</th>
            <th>ProductName</th>
            <th>Price</th>
        </tr>

        </thead>
        <tbody>

        </tbody>
    </table>
    <button type="button" class="delete-row">Delete Row</button>
    </body>
    </html>

3 个答案:

答案 0 :(得分:1)

 <body>
    <form>
       <input type="text" id="ProductName" placeholder="ProductName">
       <input type="text" id="Price" placeholder="Price">
       <input type="button" class="add-row" value="Add Row">
       <label>Amount </label>
       <input type="text" size="30" height="20" id="tot" placeholder="Total" readonly>
    </form>
 </body>

 <script>

    $(".add-row").click(function(){ 
       var ProductName = $("#ProductName").val();
       var Price = $("#Price").val();
       var tot = $("#tot").val();
       if(tot == ""){
          tot = 0;
       }
       tot = parseFloat(tot) + parseFloat(Price);

       $("#tot").val(tot);
       var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + ProductName + "</td><td>" + Price + "</td></tr>";
       $("table tbody").append(markup);
   });

   $(".delete-row").click(function(){
       $("table tbody").find('input[name="record"]').each(function(){
            if($(this).is(":checked")){
                var total = parseFloat($("#tot").val());
                var newtotal = total - parseFloat($(this).data("price"));
                $("#tot").val(newtotal);
                $(this).parents("tr").remove();
            }
       });
   });

 </script>

答案 1 :(得分:1)

var tot = 0;全局声明

为添加项目而添加

if(total="")
{
  tot = parseInt(Price);
}else{
  tot += parseInt(Price);
}

$("#tot").val(tot);

为删除项目而添加

tot -= parseInt($(this).data("price"));
$("#tot").val(tot);

 $(document).ready(function(){
 var  tot = 0;
                $(".add-row").click(function(){
                   
                    var ProductName = $("#ProductName").val();
                    var Price = $("#Price").val();
                    var markup = "<tr><td><input type='checkbox' name='record' data-price='"+ Price +"'></td><td>" + ProductName + "</td><td>" + Price + "</td></tr>";         var total = $("#tot").val();
                    if(total="")
                    {
                        tot = parseInt(Price);
                    }else{
                        tot += parseInt(Price);
                    }
                    
                    $("#tot").val(tot);
                    
                    $("table tbody").append(markup);

                });
                // Find and remove selected table rows
                $(".delete-row").click(function(){
                    $("table tbody").find('input[name="record"]').each(function(){
                        if($(this).is(":checked")){
                         //var total = $("#tot").val();
                         tot -= parseInt($(this).data("price"));
                          $("#tot").val(tot);
                            $(this).parents("tr").remove();
                        }
                    });
                });
            });
  table{
                width: 100%;
                margin: 20px 0;
                border-collapse: collapse;
            }
            table, th, td{
                border: 1px solid #cdcdcd;
            }
            table th, table td{
                padding: 5px;
                text-align: left;
            }
<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>jQuery Add / Remove Table Rows</title>
        <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  
    </head>
    <body>
    <form>
        <input type="text" id="ProductName" placeholder="ProductName">
        <input type="text" id="Price" placeholder="Price">
        <input type="button" class="add-row" value="Add Row">
        <label>Amount </label>
        <input type="text" size="30" height="20" id="tot" placeholder="Total">
    </form>
    <table>
        <thead>
        <tr>
            <th>Select</th>
            <th>ProductName</th>
            <th>Price</th>
        </tr>

        </thead>
        <tbody>

        </tbody>
    </table>
    <button type="button" class="delete-row">Delete Row</button>
    </body>
    </html>

答案 2 :(得分:0)

我可能的解决方案是创建addRowdeleteRowonRowAddedonRowDeleted方法来拆分代码,并让每种方法都发挥作用。

function addRow(product) {
    var $tableB = $('table tbody');
    var $row = $("<tr><td class=\"delete-row\"><a href=\"#\">Delete</a></td><td>" + product.name + "</td><td class=\"price\">" + product.price + "</td></tr>");
     $row.data("name", product.name);
     $row.data("price", product.price);
     $row.find('.delete-row').click(function(event) { 
         deleteRow($(event.currentTarget).parent('tr'));
     });
     $tableB.append($row);
     onRowAdded($row);
}
function deleteRow(row) {
    $(row).remove();
    onRowDeleted();
}

function onRowAdded(row) {
    updateTotal();
}

function onRowDeleted(roe) {
    updateTotal();
}

此外,我还将在dataset方法的帮助下使用.data()来存储原始值并在UI中显示自己的值。

请看小提琴以更好地理解我的方法。

$(".add-row").click(function() {
  var product = {
    name: $("#ProductName").val(),
    price: $("#Price").val()
  };
  addRow(product);
});

$(".delete-selected-row").click(function() {

  $tableB = $("table tbody");

  $tableB.find('input[name="record"]:checked').parents('tr').each(function(index, elem) {
    deleteRow($(elem));
  });
});

function addRow(product) {
  var $tableB = $('table tbody');
  var $row = $("<tr><td><input type='checkbox' name='record'></td><td class=\"delete-row\"><a href=\"#\">Delete</a></td><td>" + product.name + "</td><td class=\"price\">" + product.price + " €</td></tr>");
  $row.data("name", product.name);
  $row.data("price", product.price);
  $row.find('.delete-row').click(function(event) {
    deleteRow($(event.currentTarget).parent('tr'));
  });
  $tableB.append($row);
  onRowAdded($row);
}

function deleteRow(row) {
  $(row).remove();
  onRowRemoved();
}

function updateTotal() {
  var total = $('table tbody tr').toArray().reduce(function(pre, post) {
    return pre + parseFloat($(post).data('price'));
  }, 0);
  $('table tfoot .total').parent('tr').data('total', total);
  $('table tfoot .total').text(total + ' €');
}

function onRowAdded(row) {
  updateTotal();
}

function onRowRemoved(roe) {
  updateTotal();
}

$('.get-data').click(function() {
  console.log(getData());
});

function getData() {
  var data = {};
  data.total = $('table tfoot .total').parent('tr').data('total') || 0;
  
  data.products = $('table tbody tr')
    .toArray() // converts the jQuery node list to an array
    .map((elem) => {
      return {
        name: $(elem).data('name'),
        price: $(elem).data('price'),
      };
    }) // map the array
    ;
    
    return data;
}
table {
  width: 100%;
  margin: 20px 0;
  border-collapse: collapse;
}

table,
th,
td {
  border: 1px solid #cdcdcd;
}

table th,
table td {
  padding: 5px;
  text-align: left;
}

table td.total-title {
  text-align: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<body>
  <form>
    <input type="text" id="ProductName" placeholder="ProductName">
    <input type="text" id="Price" placeholder="Price">
    <input type="button" class="add-row" value="Add Row">
    <label>Amount </label>
  </form>
  <table>
    <thead>
      <tr>
        <th>Select</th>
        <th>Actions</th>
        <th>Product name</th>
        <th>Price</th>
      </tr>
      <tr>
        <td colspan="4"><button type="button" class="delete-selected-row">Delete Row</button></td>
      </tr>
    </thead>
    <tbody></tbody>
    <tfoot>
      <tr>
        <td colspan="3" class="total-title">Total:</td>
        <td class="total">0</td>
      </tr>
      <tr>
        <td colspan="4"><button type="button" class="delete-selected-row">Delete Row</button></td>
      </tr>
    </tfoot>
  </table>
  <button type="button" class="get-data">Get data</button>
  <pre class="output"></pre>
</body>