Skip to content

How to calculate the amount in invoice for dynamically created input field in codeigniter

I am doing invoice in CI. I want to calculate the amount and I am able to do first row’s (dynamically created). But for second-row, it’s not working. can someone help me with this?.i hope my question is clear…

My code for inserting row dynamically

 function addRow(tableID) {
  var table = document.getElementById(tableID);
  var rowCount = table.rows.length-1;
  var row = table.insertRow(rowCount);
        //Column 1
        var cell1 = row.insertCell(0);
        cell1.innerHTML = '<input type="text" name="item[]" id="item">'
        //Column 2
        var cell2 = row.insertCell(1);
        cell2.innerHTML = '<input type="number" name="qty[]" id="qty" onkeyup="calc()">';
        //Column 3
        var cell3 = row.insertCell(2);
        cell3.innerHTML = '<input type="number" name="rate[]" id="rate">';
        //Column 4
        var cell4 = row.insertCell(3);
        cell4.innerHTML = '<input type="number" name="tax[]" id="tax">';
        //Column 5
        var cell5 = row.insertCell(4);
        cell5.innerHTML = '<input type="number" name="amound[]" id="amound" readonly>';
        //Column 6
        var cell6 = row.insertCell(5);
        cell6.innerHTML = '<input id="Button" type="button" value="Delete" class="delete-row btn btn-danger"/>';
      }
      $(document).on('click', '.delete-row', function() {
        $(this).parents('tr').remove();
      });

and here is my js code for calculation

function calc(){
   var textValue1 = document.getElementById('qty').value;
   var textValue2 = document.getElementById('rate').value;
   var textValue3 = document.getElementById('tax').value;
   var mul = textValue1 * textValue2;
   var tax = mul*(textValue3/100);
   var result = +textValue2 + +tax;
   document.getElementById('amound').value = result;
 }

Answer

The main problem with your script is that you are using ID instead of Classes on your input elements. ID’s should be unique, classes can be repeated x amount of times. And you are combining vanilla javascript with jQuery javascript.

Try to compare your own code with the example script I created. Hopefully, you can see the difference and add it to your own script.

My example: https://jsfiddle.net/tnv73mL4/

var myTable = $("#myTable");
$(document).on('click', '.delete-row', function() {
  $(this).parents('tr').remove();
});
$(document).on('keyup', 'input', function() {
  inputs = $(this).parents('tr');
  calc(inputs);
});
function calc(inputs){
   var qty = inputs.find('.qty').val();
   var rate = inputs.find('.rate').val();
   var tax = inputs.find('.tax').val();
   var mul = qty * rate;
   var tax = mul*(tax/100);
   var result = +rate + +tax;
   inputs.find('.amount').val(result);
}