vivek singh
vivek singh

Reputation: 457

How two show two columns total in third one using jQuery

I have a JSON data by which I am rendering a table, inside table I have created two input fields one for Quantity and other for Total, I have one field named as selling price so what I am trying to do is for each row quantity * selling price = Total that total should be in total column of table, And also I want to show the cumulative total in a input field,

Now In above input I want to show 17

The cumulative Total, I tried using keyup but it is not working.

My total code

let data = [{
    "Item Name": "tea",
    "Selling Price": "150.0000",
    "Qty": "0",
    "Total": 0
  },
  {
    "Item Name": "ice cream",
    "Selling Price": "130.0000",
    "Qty": "0",
    "Total": 0
  },
  {
    "Item Name": "coffie",
    "Selling Price": "130.0000",
    "Qty": "0",
    "Total": 0
  },
  {
    "Item Name": "churma",
    "Selling Price": "100.0000",
    "Qty": "0",
    "Total": 0
  }
]



var itemsQuantiry1 = [];
var totalQty1 = []

function addTableDraft(tableDataDraft) {
  var col = Object.keys(tableDataDraft[0]);
  var countNum = col.filter(i => !isNaN(i)).length;
  var num = col.splice(0, countNum);
  col = col.concat(num);
  var table = document.createElement("table");
  var tr = table.insertRow(-1);
  for (var i = 0; i < col.length; i++) {
    var th = document.createElement("th");
    th.innerHTML = col[i];
    tr.appendChild(th);
    tr.classList.add("text-center");
    tr.classList.add("head")
  }
  for (var i = 0; i < tableDataDraft.length; i++) {
    tr = table.insertRow(-1);
    tr.classList.add("item-row");
    for (var j = 0; j < col.length; j++) {

      let tabCell = tr.insertCell(-1);
      var hiddenField = document.createElement("input");
      hiddenField.style.display = "none";
      var tabledata = tableDataDraft[i][col[j]];

      if (tableDataDraft[i]['Item Name'] === tableDataDraft[i][col[j]]) {
        tabCell.innerHTML = tabledata;
        tabCell.classList.add('widthTable')
        hiddenField.setAttribute('name', 'Item_Name');
        hiddenField.setAttribute('value', tabledata);

        tabCell.appendChild(hiddenField);
      }
      if (tableDataDraft[i]['Selling Price'] === tableDataDraft[i][col[j]]) {
        tabCell.innerHTML = tabledata;
        hiddenField.setAttribute('name', 'Selling_Price');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
      }



      if (tableDataDraft[i]['Qty'] === tableDataDraft[i][col[j]]) {

        var quantityField = document.createElement("input");
        quantityField.style.border = "none";
        quantityField.style["text-align"] = "right";
        quantityField.setAttribute("name", "Quantity_field");
        quantityField.setAttribute("autocomplete", "on");

        quantityField.setAttribute("value", tabledata);
        quantityField.setAttribute("index", i);
        quantityField.setAttribute("type", "tel");
        quantityField.setAttribute("required", "required");
        quantityField.classList.add("dataReset");
        quantityField.toLocaleString('en-IN');
        tabCell.appendChild(quantityField);
      }
      if (tableDataDraft[i]['Total'] === tableDataDraft[i][col[j]]) {

        var totalField = document.createElement("input");
        totalField.style.border = "none";
        totalField.style["text-align"] = "right";
        totalField.setAttribute("name", "total");
        totalField.setAttribute("autocomplete", "on");
        totalField.setAttribute("value", tabledata);
        totalField.setAttribute("index", i);
        totalField.setAttribute("type", "tel");
        totalField.setAttribute("required", "required");
        totalField.classList.add("total");
        totalField.toLocaleString('en-IN');
        tabCell.appendChild(totalField);
      }

      if (j > 1)
        tabCell.classList.add("text-right");
    }
  }
  var divContainer = document.getElementById("indentTable");
  divContainer.innerHTML = "";
  divContainer.appendChild(table);
  table.classList.add("table");
  table.classList.add("table-striped");
  table.classList.add("table-bordered");
  table.classList.add("table-hover");


}
addTableDraft(data)
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

  <title>JS Bin</title>
  <style>

  </style>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

  <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

  <!-- Popper JS -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

  <!-- Latest compiled JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>

<body>
  <input type="text" id="cumTotal" placeholder="Cum Total">
  <table id=indentTable></table>
</body>

</html>

Upvotes: 0

Views: 255

Answers (1)

54ka
54ka

Reputation: 3589

When a value is entered in the "Qty" field and press "Enter" or go to the next field. The function takes the required values and returns the calculated result to "Total".

Then the function cumTotalFunc() collects the values from total and calculates them for "Cum Total"

I hope I've been helpful

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">

    <title>JS Bin</title>
    <style>

    </style>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <!-- Popper JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>

<body>


    <input type="text" id="cumTotal" placeholder="Cum Total">
    <table id=indentTable></table>

    <script>
        let data = [{
            "Item Name": "tea",
            "Selling Price": "150.0000",
            "Qty": "0",
            "Total": 0
        },
        {
            "Item Name": "ice cream",
            "Selling Price": "130.0000",
            "Qty": "0",
            "Total": 0
        },
        {
            "Item Name": "coffie",
            "Selling Price": "130.0000",
            "Qty": "0",
            "Total": 0
        },
        {
            "Item Name": "churma",
            "Selling Price": "100.0000",
            "Qty": "0",
            "Total": 0
        }
        ]



        var itemsQuantiry1 = [];
        var totalQty1 = []

        function addTableDraft(tableDataDraft) {
            var col = Object.keys(tableDataDraft[0]);
            var countNum = col.filter(i => !isNaN(i)).length;
            var num = col.splice(0, countNum);
            col = col.concat(num);
            var table = document.createElement("table");
            var tr = table.insertRow(-1);
            for (var i = 0; i < col.length; i++) {
                var th = document.createElement("th");
                th.innerHTML = col[i];
                tr.appendChild(th);
                tr.classList.add("text-center");
                tr.classList.add("head")
            }
            for (var i = 0; i < tableDataDraft.length; i++) {
                tr = table.insertRow(-1);
                tr.classList.add("item-row");
                for (var j = 0; j < col.length; j++) {

                    let tabCell = tr.insertCell(-1);
                    var hiddenField = document.createElement("input");
                    hiddenField.style.display = "none";
                    var tabledata = tableDataDraft[i][col[j]];

                    if (tableDataDraft[i]['Item Name'] === tableDataDraft[i][col[j]]) {
                        tabCell.innerHTML = tabledata;
                        tabCell.classList.add('widthTable')
                        hiddenField.setAttribute('name', 'Item_Name');
                        hiddenField.setAttribute('value', tabledata);

                        tabCell.appendChild(hiddenField);
                    }
                    if (tableDataDraft[i]['Selling Price'] === tableDataDraft[i][col[j]]) {
                        tabCell.innerHTML = tabledata;
                        hiddenField.setAttribute('name', 'Selling_Price');
                        hiddenField.setAttribute('value', tabledata);
                        tabCell.appendChild(hiddenField);
                    }



                    if (tableDataDraft[i]['Qty'] === tableDataDraft[i][col[j]]) {

                        var quantityField = document.createElement("input");
                        quantityField.style.border = "none";
                        quantityField.style["text-align"] = "right";
                        quantityField.setAttribute("name", "Quantity_field");
                        quantityField.setAttribute("autocomplete", "on");

                        quantityField.setAttribute("value", tabledata);
                        quantityField.setAttribute("index", i);
                        quantityField.setAttribute("type", "tel");
                        quantityField.setAttribute("required", "required");
                        quantityField.classList.add("dataReset");
                        quantityField.toLocaleString('en-IN');
                        tabCell.appendChild(quantityField);
                    }
                    if (tableDataDraft[i]['Total'] === tableDataDraft[i][col[j]]) {

                        var totalField = document.createElement("input");
                        totalField.style.border = "none";
                        totalField.style["text-align"] = "right";
                        totalField.setAttribute("name", "total");
                        totalField.setAttribute("autocomplete", "on");
                        totalField.setAttribute("value", tabledata);
                        totalField.setAttribute("index", i);
                        totalField.setAttribute("type", "tel");
                        totalField.setAttribute("required", "required");
                        totalField.classList.add("total");
                        totalField.toLocaleString('en-IN');
                        tabCell.appendChild(totalField);
                    }

                    if (j > 1)
                        tabCell.classList.add("text-right");
                }
            }
            var divContainer = document.getElementById("indentTable");
            divContainer.innerHTML = "";
            divContainer.appendChild(table);
            table.classList.add("table");
            table.classList.add("table-striped");
            table.classList.add("table-bordered");
            table.classList.add("table-hover");

            calculateTotal();

        }
        addTableDraft(data);

        function calculateTotal() {

            var list = document.getElementsByClassName('dataReset');
            for (let i = 0; i < list.length; i++) {
                list[i].addEventListener("change", function () {

                    var y = this.parentElement;
                    var z = y.parentElement;

                    var w = z.getElementsByTagName('td')[1].innerText;
                    var t = z.getElementsByClassName('total')[0];

                    var res = w * this.value;

                    t.setAttribute('value', res);

                    cumTotalFunc();
                });
            }
        }


        function cumTotalFunc() {
            var ct = document.getElementById('cumTotal');
            var t = document.getElementsByClassName('total');
            var res = 0;
            for (let i = 0; i < t.length; i++) {
                res += +t[i].value;
            }

            ct.setAttribute('value', res);
        }

    </script>

</body>
</html>

I fixed bug in my code: If the value returns to 0 now work


If in your code you add an attribute data-price with price value on element with name name="Quantity_field"

You can replace this line:

var w = z.getElementsByTagName('td')[1].innerText;

with this

var w = this.getAttribute('data-price');

That would be a better solution!

Upvotes: 2

Related Questions