Home > OS >  Why is this HTML table calculation not showing the total?
Why is this HTML table calculation not showing the total?

Time:07-24

Just started diving into JS and Jquery and I can't find out why this is not calculating the table's qty by price when the function is called without any parameter passed.

function add_to_total(el) {
  if (el) {
    var parent = $(el).closest('tr');
    var price = parent.find('.price').val();
    var qty = parent.find('.qty').val();
    if (price == '' || qty == '') {
      alert('Please make sure that the price and metros are informed correctly.');
      return;
    }
    var total = (price * qty);
    total = total.toFixed(2);
    parent.find('.total_price').html("$"   total);
  } else {


//THIS IS THE PIECE THAT DOESN'T SEEM TO RUN
    $("#tableRows tr").each(function() {
      $(this).find('.total_price').val(parseFloat($(this).find('.qty').val()) * parseFloat($(this).find('.price').val()));
    });
    console.log('Row Total: '   $(this).find('.total_price').val(parseFloat($(this).find('.qty').val()) * parseFloat($(this).find('.price').val())))
  }

  var gridTotal = 0;
  $(".total_price").each(function(index, item) {
    var val = parseFloat($(this).html().replace(/[$,]/g, ''));
    if (isNaN(val)) val = 0;
    gridTotal  = val;
  });
  $('.total').html('$'   gridTotal.toFixed(2));
}
<table  id="dtable">
  <thead>
    <tr>
      <th style="width:7%">Precio/m (COP)</th>
      <th style="width:8%">Metros (m)</th>
      <th style="width:10%">Precio Total sin IVA</th>
    </tr>
  </thead>
  <tbody id="tableRows">
    <tr>
      <td><input type="number" step="0.01" min="0"  name="numberInputs" value="3.91" onchange="add_to_total(this)"></td>
      <td><input type="number" min="0"  name="numberInputs" value="124" onchange="add_to_total(this)"></td>
      <td ><strong>$0.00</strong></td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td id="totalTitle" colspan="8" align="right"><strong>Total:</strong></td>
      <td id="totalValue" >$0.00</td>
    </tr>
  </tfoot>
</table>
<script>
//add_to_total()
</script>

...and I could use a helping hand.

CodePudding user response:

Since total_price is a table cell, you can't use .val() to change it's value. Use .html() or .text(). Val is used for inputs.

function add_to_total(el) {
  if (el) {
    var parent = $(el).closest('tr');
    var price = parent.find('.price').val();
    var qty = parent.find('.qty').val();
    if (price == '' || qty == '') {
      alert('Please make sure that the price and metros are informed correctly.');
      return;
    }
    var total = (price * qty);
    total = total.toFixed(2);
    parent.find('.total_price').html("$"   total);
  } else {

    $("#tableRows tr").each(function() {
      $(this).find('.total_price').text(parseFloat($(this).find('.qty').val()) * parseFloat($(this).find('.price').val()));
    });
    console.log('Row Total: '   $(this).find('.total_price').val(parseFloat($(this).find('.qty').val()) * parseFloat($(this).find('.price').val())))
  }

  var gridTotal = 0;
  $(".total_price").each(function(index, item) {
    var val = parseFloat($(this).html().replace(/[$,]/g, ''));
    if (isNaN(val)) val = 0;
    gridTotal  = val;
  });
  $('.total').html('$'   gridTotal.toFixed(2));
}

add_to_total();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table  id="dtable">
  <thead>
    <tr>
      <th style="width:7%">Precio/m (COP)</th>
      <th style="width:8%">Metros (m)</th>
      <th style="width:10%">Precio Total sin IVA</th>
    </tr>
  </thead>
  <tbody id="tableRows">
    <tr>
      <td><input type="number" step="0.01" min="0"  name="numberInputs" value="3.91" onchange="add_to_total(this)"></td>
      <td><input type="number" min="0"  name="numberInputs" value="124" onchange="add_to_total(this)"></td>
      <td ><strong>$0.00</strong></td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td id="totalTitle" colspan="8" align="right"><strong>Total:</strong></td>
      <td id="totalValue" >$0.00</td>
    </tr>
  </tfoot>
</table>

CodePudding user response:

You have not written the add_to_total function correctly, use the function I have created, it will run fast and correctly.

        function add_to_total() {
            let price = $(".price").val(),
                qty = $(".qty").val(),
                totalPrice = $(".total_price"),
                totalValue = $(".total"),
                calPrice = (price * qty).toFixed(2); // calculate price

            if (price || qty) {
                totalPrice.text(`$${calPrice}`)
                totalValue.text(`$${calPrice}`)
            } else {
                alert('Please make sure that the price and metros are informed correctly.');
            }
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table  id="dtable">
        <thead>
            <tr>
                <th style="width:7%">Precio/m (COP)</th>
                <th style="width:8%">Metros (m)</th>
                <th style="width:10%">Precio Total sin IVA</th>
            </tr>
        </thead>
        <tbody id="tableRows">
            <tr>
                <td><input type="number" step="0.01" min="0"  name="numberInputs" value="3.91"
                        onkeyup="add_to_total(this)" onchange="add_to_total(this)"></td>
                <td><input type="number" min="0"  name="numberInputs" value="124"
                        onkeyup="add_to_total(this)" onchange="add_to_total(this)""></td>
                <td ><strong>$0.00</strong></td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td id="totalTitle" colspan="8" align="right"><strong>Total:</strong></td>
                <td id="totalValue" >$0.00</td>
            </tr>
        </tfoot>
    </table>

  • Related