Подсчитайте общую стоимость цены в таблице col, которую можно вставить вручную - PullRequest
0 голосов
/ 19 сентября 2019

Я ищу помощь в простом решении проблемы.Нужно рассчитать общую стоимость всех существующих значений в таблице.Который добавлен, нажав добавить цену продукта в нижней части таблицы.

Простой 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

Ответы [ 3 ]

1 голос
/ 19 сентября 2019

Я добавил битовый код для проверки вашего кода ниже, только что добавил функцию для вычисления суммы с этим кодом .... дайте мне знать, если у вас есть какие-либо сомнения по поводу этого кода.

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

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

    }
];


$.each(products, function(i, product) {
    appendToProductTable(product);
});

$("form").submit(function(e) {
    e.preventDefault();
});
calTotal();
function calTotal(){
  var count=0;
  $('#productTable tr').each(function(){
    if(($(this).find('td').length) > 0){
      count = count + parseInt($(this).find('td:last-child').html());
    }
  });       
  $('#Tprice').html(count);
  }
                     
$("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.");
    }
  
  calTotal();
});

function addProduct(product) {
    products.push(product);
    appendToProductTable(product);
}
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>   
    `);

}
body, html {
    font-size: 16px;
}
.container{
    max-width: 1170px !important; ;}

.main-title h1{
    margin: 1em 0;
}
.table {
    width: 100%;
    margin-bottom: 1rem;
    background-color: transparent;
}
.table-striped tbody tr:nth-of-type(odd) {
    background-color: rgba(0,0,0,.05);
}
.table td, .table th {
    padding: .75rem;
    vertical-align: top;
    border-top: 1px solid #dee2e6;
}
.form-control {
    display: block;
    width: 100%;
    height: calc(2.25rem + 2px);
    padding: .375rem .75rem;
    font-size: 1rem;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.btn-primary:not(:disabled):not(.disabled).active, .btn-primary:not(:disabled):not(.disabled):active, .show>.btn-primary.dropdown-toggle {
    color: #fff;
    background-color: #0062cc;
    border-color: #005cbf;
}
<link rel="stylesheet" id="cf_styles-css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" type="text/css" media="screen,projection" />
<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>
                </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>
                <table id="TotalPrice" class="table table-striped">
                    <tr>
                        <td>Total</td>
                        <td  id="Tprice"></td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
1 голос
/ 19 сентября 2019

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>

Примечание: - Просто вам нужно сначала вызвать функцию!

0 голосов
/ 19 сентября 2019

Вот небольшой фрагмент кода, который накапливает и отображает общую стоимость:

$("#getTotal").click(showTotalPrice);

function showTotalPrice() {
    let totalPrice = 0;
    $("#productTable td[name='price']").each(function(index, value) {                
        totalPrice += parseInt($(this).text());
    });
    $("#priceAlert #priceAlertMsg").text("The total price is " + totalPrice);
    $("#priceAlert").show();
}

HTML, добавленный чуть ниже таблицы, выглядит следующим образом:

<div class="col-sm-4">
  <button id="getTotal" class="btn btn-primary form-control" type="button">GET TOTAL PRICE</button>
</div>
<div class="col-sm-8">
  <div id="priceAlert" class="alert alert-primary alert-dismissible fade show" role="alert">
    <div id="priceAlertMsg"></div>
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
</div>

Новая ручка разветвленаот вашего доступен на https://codepen.io/danypack/pen/qBWQBRZ. Не уверен, что это все, что вам нужно, но надеюсь, что это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...