Calculating the total of the products with Javascript

0

I am trying to add products to a shopping table, which works well, the problem comes when calculating, between the quantity of the product and the price, however, when changing the quantity, this is not the calculates, I had a certain inconvenience when defining this calculation since the field of #producto-quantity does not exist previously, but is created later with Javascript, so it is difficult for me to extract its id previously to be able to capture its value, and so can calculate it, I appreciate your help to do this correctly, I share my code below, the error is more specifically in the section commented as: //Create New HTML Element

<div class="container py-5">

  <div class="row">
    <!-- Product List -->
    <div class="col-sm-6">

      <h2>Productos <%= link_to 'Nuevo producto', new_product_path, class: "btn btn-sm btn-primary float-right" %></h2>

      <table class="table" id="products">
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Price</th>
            <th class="text-right">Opciones</th>
          </tr>
        </thead>

        <tbody>
          <tr>
              <td class="product-id">1</td>
              <td class="product-name">Manzana</td>
              <td class="product-price">0.25</td>
              <td><button class="add-product btn btn-primary">Agregar</button></td>
          </tr>
          <tr>
              <td class=product-id">2</td>
              <td class="product-name">Sandia</td>
              <td class="product-price">0.45</td>
              <td><button class="add-product btn btn-primary">Agregar</button></td>
          </tr>
          <tr>
              <td class="product-id">3</td>
              <td class="product-name">Uva</td>
              <td class="product-price">0.25</td>
              <td><button class="add-product btn btn-primary">Agregar</button></td>
          </tr>
        </tbody>
      </table>

    </div>
    <!-- Sale -->
    <div class="col-sm-6">
      <h2>Venta</h2>

      <table class="table" id="shopping-list">
          <thead>
            <tr>
                <th>ID</th>
                <th>Nombre</th>
                <th>Precio Unit.</th>
                <th>Cant.</th>
                <th>Precio Total</th>
                <th>Acciones</th>
            </tr>        
          </thead>
          <tbody></tbody>
      </table>                

    </div>

  </div>

</div>

<script>

// Get Product Data
function addProduct(e){

  //Get HTML Element
  const getElement = e.target.parentElement.parentElement;

  const product = {
    id: getElement.querySelector('.product-id').textContent,
    name: getElement.querySelector('.product-name').textContent,
    price: getElement.querySelector('.product-price').textContent
  }

  // Create New HTML Element 
  const newElement = document.createElement('tr');

  let quantity = 1;
  let itemPrice = product.price * quantity;

  newElement.innerHTML = '
      <td>${ product.id }</td>
      <td>${ product.name }</td>
      <td>${ product.price }</td>
      <td><input type="number" name="quantity" class="product-quantity form-control" step="any" value="${ quantity }" /></td>
      <td>${ itemPrice }</td>
      <td><a href="" class="remove-item" id="${ product.id }">X</a></td>
  ';

  // Add Product to Shopping List
  const shoppingList = document.querySelector('#shopping-list tbody');
  shoppingList.appendChild(newElement);

}

// Get All ID Button
let addThis = document.getElementsByClassName('add-product');

for (let i = 0; i < addThis.length; i++){
  addThis[i].addEventListener('click', addProduct);
}

</script>
    
asked by Hector Hernandez 13.10.2018 в 08:50
source

1 answer

0

I have added an event listener for each input type="number" ; Each time you change the number, I recalculate the subtotal for the product and the total of the entire basket.

For the input type number I added min = 0 because I do not think it is possible to buy -1 grapes. If you want to return products you can delete min = 0;

const shoppingList = document.querySelector('#shopping-list tbody');

// Get Product Data
function addProduct(e){

  //Get HTML Element
  const getElement = e.target.parentElement.parentElement;

  const product = {
    id: getElement.querySelector('.product-id').textContent,
    name: getElement.querySelector('.product-name').textContent,
    price: getElement.querySelector('.product-price').textContent
  }

  // Create New HTML Element 
  const newElement = document.createElement('tr');

  let quantity = 1;
  let itemPrice = product.price * quantity;

  newElement.innerHTML = '
      <td>${ product.id }</td>
      <td>${ product.name }</td>
      <td>${ product.price }</td>
      <td><input type="number" name="quantity" class="product-quantity form-control" step="any" value="${ quantity }" min="0" /></td>
      <td class="st">${ itemPrice }</td>
      <td><a href="" class="remove-item" id="${ product.id }">X</a></td>
  ';

  // Add Product to Shopping List

  shoppingList.appendChild(newElement);
  calculaElTotal();

}

// Get All ID Button
let addThis = document.getElementsByClassName('add-product');

for (let i = 0; i < addThis.length; i++){
  addThis[i].addEventListener('click', addProduct);
}


shoppingList.addEventListener("input", (e)=>{
  if(e.target.type == "number"){
    let unidades = Number(e.target.value); console.log(unidades);
    
    let tr = e.target.parentNode.parentNode;
    
    let precioUnitario = Number(tr.querySelectorAll("td")[2].textContent);console.log(precioUnitario)
    
    let subTotal = unidades * precioUnitario;console.log(subTotal)
    
    let precioTotal = tr.querySelectorAll("td")[4];
    precioTotal.textContent = subTotal;
     
  }
  
calculaElTotal();
})

function calculaElTotal(){
   let total = 0; 
   let tdsArray = Array.from(shoppingList.getElementsByClassName("st"));
   tdsArray.forEach(td =>{
   
   total += Number(td.textContent);console.log(total)
   valor_total.textContent = total;
 })
  
}
th,td{border:1px solid}
<div class="container py-5">

  <div class="row">
    <!-- Product List -->
    <div class="col-sm-6">

      <h2>Productos: 'Nuevo producto', new_product_path, class: "btn btn-sm btn-primary float-right" </h2>

      <table class="table" id="products">
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Price</th>
            <th class="text-right">Opciones</th>
          </tr>
        </thead>

        <tbody>
          <tr>
              <td class="product-id">1</td>
              <td class="product-name">Manzana</td>
              <td class="product-price">0.25</td>
              <td><button class="add-product btn btn-primary">Agregar</button></td>
          </tr>
          <tr>
              <td class="product-id">2</td>
              <td class="product-name">Sandia</td>
              <td class="product-price">0.45</td>
              <td><button class="add-product btn btn-primary">Agregar</button></td>
          </tr>
          <tr>
              <td class="product-id">3</td>
              <td class="product-name">Uva</td>
              <td class="product-price">0.25</td>
              <td><button class="add-product btn btn-primary">Agregar</button></td>
          </tr>
        </tbody>
      </table>

    </div>
    <!-- Sale -->
    <div class="col-sm-6">
      <h2>Venta</h2>

      <table class="table" id="shopping-list">
          <thead>
            <tr>
                <th>ID</th>
                <th>Nombre</th>
                <th>Precio Unit.</th>
                <th>Cant.</th>
                <th>Precio Total</th>
                <th>Acciones</th>
            </tr>        
          </thead>
          <tbody></tbody>
      </table>                

    </div>

  </div>

</div>



<div id="valor_total"></div>
    
answered by 13.10.2018 / 12:15
source