首页 > 解决方案 > 计算表col中价格的总成本,可以手动插入

问题描述

我正在寻找问题的简单解决方案的帮助。需要计算表中所有现有值的总价。通过单击表格底部的添加产品价格添加。

简单的 JavaScript 和 Jquery

$("form#addProduct").submit(function() {
    var product = {};
    var nameInput = $('input[name="name"]').val().trim();
    var priceInput = $('input[name="price"]').val().trim();
    if (nameInput && priceInput ) {
        $(this).serializeArray().map(function(data) {
            product[data.name] = data.value;
        });
        var lastProduct = products[Object.keys(products).sort().pop()];
        product.id = lastProduct.id + 1;

        addProduct(product);
    } else {
        alert("All fields must have a valid value.");
    }
});

完整代码在链接 CodePen https://codepen.io/ajdos-zhubandyk/pen/pozQzNd

总成本为 120

标签: javascriptjquery

解决方案


var products = [{
    id: 1,
    name: "Apple",
    price: 70,

  },
  {
    id: 2,
    name: "Lemon",
    price: 50,

  }
];
var totalPrice = 0;
TotalPrice();
$.each(products, function(i, product) {
  appendToProductTable(product);
});
$("form").submit(function(e) {
  e.preventDefault();
});
$("form#addProduct").submit(function() {
  var product = {};
  var nameInput = $('input[name="name"]').val().trim();
  var priceInput = $('input[name="price"]').val().trim();
  if (nameInput && priceInput) {
    $(this).serializeArray().map(function(data) {
      product[data.name] = data.value;
    });
    var lastProduct = products[Object.keys(products).sort().pop()];
    product.id = lastProduct.id + 1;
    addProduct(product);
  } else {
    alert("All fields must have a valid value.");
  }
});

function addProduct(product) {
  products.push(product);
  TotalPrice();
  appendToProductTable(product);
}

function TotalPrice() {
  for (var i = 0; i < products.length; i++) {
    totalPrice = totalPrice + parseInt(products[i].price);
    $("#totalPrice").html(totalPrice);
  }
}

function appendToProductTable(product) {
  $("#productTable > tbody:last-child").append(`
        <tr id="product-${product.id}">
            <td class="productData" name="name">${product.name}</td>
            '<td class="productData" name="price">${product.price}</td>            
        </tr>     
        <tr></tr>   
    `);

}

function calculateSum() {
  var sum = 0;
  //iterate through each textboxes and add the values
  $(".productData").each(function() {
    //add only if the value is number
    if (!isNaN(this.value) && this.value.length != 0) {
      sum += parseFloat(this.value);
    }

  });
  //.toFixed() method will roundoff the final sum to 2 decimal places
  //$("#sum").html(sum.toFixed(2));
}
calculateSum();
body,
html {
  font-size: 16px;
}

.container {
  max-width: 1170px !important;
  ;
}

.main-title h1 {
  margin: 1em 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <div class="main-title">
        <h1>Please add the Product</h1>
        <span id='totalPrice'></span>
      </div>
    </div>
    <div class="col-sm-4">
      <form id="addProduct" action="">
        <div class="form-group">
          <input class="form-control" type="text" name="name" placeholder="Name" required>
        </div>
        <div class="form-group">
          <input class="form-control" type="number" name="price" min="0" placeholder="Price" required>
        </div>
        <button class="btn btn-primary form-control" type="submit">SUBMIT</button>
      </form>
    </div>
    <div class="col-sm-12">
      <div class="main-title">
        <h1>Products</h1>
      </div>
      <table id="productTable" class="table table-striped">
        <tr>
          <th>Name</th>
          <th>Price.tg</th>
        </tr>
      </table>
    </div>
  </div>
</div>

$(document).ready(function() {
  //iterate through each textboxes and add keyup
  //handler to trigger sum event
  //call initially
  calculateSum();
  $(".txt").each(function() {

    $(this).keyup(function() {
      calculateSum();
    });
  });

});

function calculateSum() {

  var sum = 0;
  //iterate through each textboxes and add the values
  $(".txt").each(function() {

    //add only if the value is number
    if (!isNaN(this.value) && this.value.length != 0) {
      sum += parseFloat(this.value);
    }

  });
  //.toFixed() method will roundoff the final sum to 2 decimal places
  $("#sum").html(sum.toFixed(2));
}
body {
  font-family: sans-serif;
}

#summation {
  font-size: 18px;
  font-weight: bold;
  color: #174C68;
}

.txt {
  background-color: #FEFFB0;
  font-weight: bold;
  text-align: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">
  <tr>
    <td width="40px">1</td>
    <td>Butter</td>
    <td><input class="txt" type="text" name="txt" value='100' /></td>
  </tr>
  <tr>
    <td>2</td>
    <td>Cheese</td>
    <td><input class="txt" type="text" name="txt" value='50' /></td>
  </tr>
  <tr>
    <td>3</td>
    <td>Eggs</td>
    <td><input class="txt" type="text" name="txt" value='50'/></td>
  </tr>
  <tr>
    <td>4</td>
    <td>Milk</td>
    <td><input class="txt" type="text" name="txt" value='100' /></td>
  </tr>
  <tr>
    <td>5</td>
    <td>Bread</td>
    <td><input class="txt" type="text" name="txt" value='100'/></td>
  </tr>
  <tr>
    <td>6</td>
    <td>Soap</td>
    <td><input class="txt" type="text" name="txt" value='100' /></td>
  </tr>
  <tr id="summation">
    <td>&nbsp;</td>
    <td align="right">Sum :</td>
    <td align="center"><span id="sum">0</span></td>
  </tr>
</table>

注意:- 只需您最初需要调用函数!


推荐阅读