简体   繁体   中英

jQuery calculation in table td loop

I am getting the JSON data through PHP. I am trying to calculate the value of td with the help of javascript and jQuery and calculate the opening and closing balance as below like the table example.

is this possible to do that? Please help me How I implement with jquery in my jQuery code.

Example table -

open bal as 0 first time + today in - today out = closing bal and previous closing bal will be open bal next day .

open bal today in today out closing bal
1 1 1 1
2 0 1 1
0 2 0 2

 $.ajax({ type: "POST", cache: false, }, success: function(response) { if (response == "ok") { $.each(response.data, function(i, items) { tableWithHeader.find('tbody').append(` <tr> <td>0</td> <td>${items.inqty}</td> <td>${items.outqty}</td> <td></td> </tr> `); }); } });

Here:

$.ajax({
    type: "POST",
    cache: false,
  },
  success: function(response) {
    if (response == "ok") {
      let openqty = 0 // declare outside of loop
      let closeqty = 0 // declare outside of loop
      $.each(response.data, function(i, items) {
      
      closeqty = parseInt(items.inqty) - parseInt(items.outqty) + openqty
      //calculate closeqty
        tableWithHeader.find('tbody').append(`
     <tr>
      <td>${openqty}</td>  // this will be 0 on first run
      <td>${items.inqty}</td>
      <td>${items.outqty}</td>
      <td>${closeqty}</td>
      </tr>
    `);
      });
      openqty = closeqty // now set it for next loop to be same as closeqty 
    }
  });

Working example:

 //$.ajax({ //type: "POST", //cache: false, //}, //success: function(response) { //if (response == "ok") { let openqty = 0 // declare outside of loop let closeqty = 0 // declare outside of loop const response = { data: [{ inqty: "2", outqty: "0" }, { inqty: "0", outqty: "1" }, { inqty: "1", outqty: "1" }] } // sample data $.each(response.data, function(i, items) { closeqty = parseInt(items.inqty) - parseInt(items.outqty) + openqty //calculate closeqty $("table").find('tbody').append(` <tr> <td>${openqty}</td> // this will be 0 on first run <td>${items.inqty}</td> <td>${items.outqty}</td> <td>${closeqty}</td> </tr> `); openqty = closeqty // now set it for next loop to be same as closeqty });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tbody> </tbody> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM