Muhammad Ashikuzzaman
Muhammad Ashikuzzaman

Reputation: 103

A function not working when creating new row on table

I have a html table where I add rows dynamically when user clicks on a button. Two cell's number of each row of my table, should be multiplied. I made a function that can multiply 2 cell's number but when I create a new row by pressing add button the function does not work on the new row, it always works on first row on the table.

Here is HTML code:

<div class="table-responsive container">
    <table class="table">
        <thead class="dark">
        <tr>
            <th scope="col">SL.</th>
            <th scope="col">Item Description</th>
            <th scope="col">Price</th>
            <th scope="col">Qty.</th>
            <th scope="col">Total</th>
            <th scope="col">Del</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <th scope="row">1</th>
            <td><label>
                <input type="text" name="name">
            </label>
            </td>
            <td><label>
                <input type="text" id="price" oninput="calculate()">
            </td>
            <td>
                <input type="text" id="qt" oninput="calculate()">
            </td>
            <td>
                <input type="text" id="ttl" name='total'>
            </td>
            <td>
                <button class="remove">-</button>
            </td>
        </tr>
        </tbody>
    </table>
    <button id="addRow">+ Add</button>
</div>

And here is the JavaScript code:

let temp_td = '<tr>' +
    '<th scope="row">1</th>' +
    '<td><label><input type="text" name="name"></label></td>' +
    '<td><label><input type="text" id="price" oninput="calculate()"></td>' +
    '<td><input type="text" id="qt" oninput="calculate()"></td>' +
    '<td><input type="text" id="ttl" name="total"></td>' +
    '<td><button class="remove">-</button></td>' +
'</tr>';

$(function () {
    $('tbody').sortable();

    $('#addRow').click(function () {
        $('tbody').append(temp_td)
    });

    $(document).on('click', '.remove', function () {
        $(this).parents('tr').remove();
    });

    $('#getValues').click(function () {
        const total = [];
        let sum = 0;
        $('input[name="total"]').each(function (i, elem) {
            total.push($(elem).val())
        });
        for (let i = 0; i < total.length; i++) {
            sum += Number(total[i])
        }
        console.log(total.join(','));
        console.log(total);
        console.log(sum);
        document.getElementById('subtotal').innerHTML = sum;
        document.getElementById('total').innerHTML = sum + (sum * 5 / 100);

        // document.getElementById('total22').innerHTML = sum;
    })

});
function calculate() {
    var price = document.getElementById('price').value; 
    var qt = document.getElementById('qt').value;
    var ttl = document.getElementById('ttl');   
    var multiply = price * qt;
    ttl.value = multiply;
}

I tried to change so many things, but it's not working.

Upvotes: 0

Views: 452

Answers (1)

Racil Hilan
Racil Hilan

Reputation: 25361

You cannot duplicate the IDs in HTML. You can save the row number in a variable which you increment every time you add a new row, and use that variable to generate the IDs:

$(function() {
  let row = 1;

  $('#addRow').click(function() {
    row++;
    let temp_td = '<tr><th scope="row">' + row + '</th><td><label><input type="text" name="name"></label></td><td><label><input type="text" id="price' + row + '" oninput="calculate(' + row + ')"></td><td><input type="text" id="qt' + row + '" oninput="calculate(' + row + ')"></td><td><input type="text" id="ttl' + row + '" name="total"></td><td><button class="remove">-</button></td></tr>';
    $('tbody').append(temp_td)
  });

  $(document).on('click', '.remove', function() {
    $(this).parents('tr').remove();
  });
});

function calculate(r) {
  var price = document.getElementById('price' + r).value;
  var qt = document.getElementById('qt' + r).value;
  var ttl = document.getElementById('ttl' + r);
  var multiply = price * qt;
  ttl.value = multiply;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="table-responsive container">
  <table class="table">
    <thead class="dark">
      <tr>
        <th scope="col">SL.</th>
        <th scope="col">Item Description</th>
        <th scope="col">Price</th>
        <th scope="col">Qty.</th>
        <th scope="col">Total</th>
        <th scope="col">Del</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th scope="row">1</th>
        <td><label>
                    <input type="text" name="name">
                </label>
        </td>
        <td><label>
                    <input type="text" id="price1" oninput="calculate(1)">
                </td>
                <td>
                    <input type="text" id="qt1" oninput="calculate(1)">
                </td>
                <td>
                    <input type="text" id="ttl1" name='total'>
                </td>
                <td>
                    <button class="remove">-</button>
                </td>
            </tr>
            </tbody>
        </table>
        <button id="addRow">+ Add</button>

You can also do that to the names if you like. I didn't do that in the code above because it is not essential for this answer.

Alternatively, you can pass the element itself to the calculate() function and then find the other "sibling" elements using jQuery. So you don't need IDs at all.

Upvotes: 1

Related Questions