JavaScript – Need sum of total price from all rows in total input but it concatenates the values together instead of adding them

I want to sum the total price of all rows in total. But it can not add the value it just concatenates the values. Here’s PHP that generates the HTML:

$counter = 0;

foreach($db->getRecordSet($sqlTrRecord) as $row){$counter += 1; ?>
    <tr id="temTr" class="banktblhd">
      <td width="5"> <?php echo($counter); ?> </td>

      <td class="w10"> <input type="number" name="item_code" id="item_code" class="form-control" value="<?php echo($row['item_code']); ?>" readonly  /></td>
      <td class="w10"><input type="text" class="form-control" name="item_name" id="item_name" value="<?php echo($row['item_name']); ?>" readonly /> </td>
      <td class="w10"><input type="text" class="form-control" name="description" id="description" value="<?php echo($row['description']); ?>" readonly /></td>
      <td class="w10"><input type="number" class="form-control" name="availableQty" id="availableQty" value="<?php echo($row['quantity']); ?>" readonly  /></td>
      <td class="w10"><input type="number" class="form-control" name="p_cost" oninput="total(this);" id="p_cost" value="<?php echo($row['p_cost']); ?>" readonly /></td>
      <td class="w10">
        <input type="number" oninput="total(this);" class="form-control" name="quantity" id="quantity" autocomplete="off" /> </td>
      <td class="w10">
        <input type="number" oninput="total(this);" class="form-control" name="sale" id="sale" autocomplete="off" /> </td> 
      <td class="w10"><input type="number" oninput="total(this)" class="form-control" name="total_price" id="total_price" readonly />
      <td class="w10" colspan="2"><input type="number" class="form-control"  name="total" id="total" readonly /></td>

and here’s my JavaScript:

function total(element) {
    var row = element.closest("tr");
    var unitRate = row.querySelector("input[name=p_cost]");
    var qty = row.querySelector("input[name=quantity]");
    var sale = row.querySelector("input[name=sale]");

    var total_price = parseFloat(unitRate.value * qty.value) + parseFloat(sale.value);
    var total = row.querySelector("input[name=total_price]").value = total_price;

    document.getElementById("total").value += total;

83 thoughts on “JavaScript – Need sum of total price from all rows in total input but it concatenates the values together instead of adding them”

  1. Pingback: priligy approval