logo
Tags down

shadow

DOM Dynamic Table calculation


By : user2174689
Date : October 17 2020, 08:10 AM
I wish did fix the issue. Try this:
In line 44 of the Javascript code on Codepen, replace colSum3 with colSum + colSum2.
code :
tableNode.rows[8].cells[3].innerHTML = colSum + colSum2;


Share : facebook icon twitter icon

Bug in the calculation of total in a dynamic table


By : EdR
Date : March 29 2020, 07:55 AM
should help you out The problem comes from the fact that when you delete a row inside a table (not the last one) you have a gap in ids. getElementById will return null and your total function will raise an exception.
Add 3 products: idx is 3, ids in the DOM are 0, 1, 2; Remove product 1: idx is 2, ids in the DOM are 0, 2; => total will throw for i == 1
code :
function total()
{
    var total = 0,
        prices = document.querySelectorAll('.price'),
        quantities = document.querySelectorAll('.quantity'), 
        i = 0, len = prices.length;

    for(; i < len; i++) {
        total += prices[i].value*quantities[i].value;    
    }

    document.getElementById('total').value = total;
}

jQuery dynamic table calculation


By : Elisa Gonzales-Magui
Date : March 29 2020, 07:55 AM
around this issue I've made an example on how you can do this on jsFiddle: https://jsfiddle.net/gtcazp7s/
code :
    // main function when page is opened
    $(document).ready(function () {

        // function for adding a new row
        var r = 1;
        $('.addRow').click(function () {
            r++;
            $('#t1').append('<tr id="row' + r + '" class="item"><td><select name="personal"><optgroup label="Personal"><option value="k&ouml;che">K&ouml;che</option><option value="barkeeper">Barkeeper</option><option value="garderobiere">Garderobiere</option><option value="chauffeure">Chauffeure</option><option value="oberkellner">Oberkellner</option><option value="serviceleitung">Serviceleitung</option><option value="hilfskoch">Hilfskoch</option><option value="servicekr&auml;fte">Servicekr&auml;fte</option></optgroup></select></td><td><input class="qnty amount" value="" /></td><td><input class="price amount" value="" /></td><td><input class="hours amount" value="" /></td><td><input class="total" value="" readonly="readonly" /></td><td><button type="button" name="remove" id="' + r + '" class="btn_remove">X</button></td></tr>');
        });
        // remove row when X is clicked
        $(document).on('click', '.btn_remove', function () {
            var button_id = $(this).attr("id");
            $('#row' + button_id + '').remove();
        });
        // calculate everything
        $(document).on("keyup", ".amount", calcAll);
        //$(".amount").on("change", calcAll);
    });

    // function for calculating everything
    function calcAll() {
        // calculate total for one row

        $(".item").each(function () {
            var qnty = 1;
            var price = 1;
            var hours = 1;
            var total = 1;
            if (!isNaN(parseFloat($(this).find(".qnty").val()))) {
                qnty = parseFloat($(this).find(".qnty").val());
            }
            if (!isNaN(parseFloat($(this).find(".price").val()))) {
                price = parseFloat($(this).find(".price").val());
            }
            if (!isNaN(parseFloat($(this).find(".hours").val()))) {
                hours = parseFloat($(this).find(".hours").val());
            }
            total = qnty * price * hours;
            $(this).find(".total").val(total.toFixed(2));
        });

        //$(".amount").each(function () {

        //    if (!isNaN(this.value) && this.value.length != 0) {
        //        product *= parseFloat(this.value);
        //    }
        //    $("#total1").val(product.toFixed(2));
        //    if (!isNaN($(this).find(".qnty"))) {

        //    }
        //});

        // sum all totals
        var sum = 0;
        $(".total").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                sum += parseFloat(this.value);
            }
        });
        // show values in netto, steuer, brutto fields
        // show values in netto, steuer, brutto fields
        $("#netto").val(sum.toFixed(2));
        $("#steuer").val(parseFloat(sum * 0.19).toFixed(2));
        $("#brutto").val(parseFloat(sum.toFixed(2) + parseFloat(($("#steuer").val()))).toFixed(2));
    }
<div>
    <h2>Offer</h2>
    <form>
        <table id="t1">
            <tr>
                <th><button type="button" class="addRow">Add</button></th>
                <th>Quantity</th>
                <th>Price per hour</th>
                <th>Hours</th>
                <th>Total</th>
            </tr>
            <tr class="item">
                <td><select name="personal"><optgroup label="Personal"><option value="k&ouml;che">K&ouml;che</option><option value="barkeeper">Barkeeper</option><option value="garderobiere">Garderobiere</option><option value="chauffeure">Chauffeure</option><option value="oberkellner">Oberkellner</option><option value="serviceleitung">Serviceleitung</option><option value="hilfskoch">Hilfskoch</option><option value="servicekr&auml;fte">Servicekr&auml;fte</option></optgroup></select></td>
                <td><input name="anzahl" class="qnty amount" value="" /></td>
                <td><input name="preisps" class="price amount" value="" /></td>
                <td><input name="stunden" class="hours amount" value="" /></td>
                <td><input name="total" class="total" id="total1" value="" readonly="readonly" /></td>
            </tr>
        </table>

        <br />

        <table id="t2">
            <tr>
                <td>Netto =<br></td>
                <td><input id="netto" readonly="readonly" name="netto" type="text" value=""></td>
            </tr>
            <tr>
                <td>Steuer 19% =<br></td>
                <td><input id="steuer" readonly="readonly" name="steuer" type="text" value=""></td>
            </tr>
            <tr>
                <td>Brutto =<br></td>
                <td><input id="brutto" readonly="readonly" name="brutto" type="text" value=""></td>
            </tr>
        </table>
        <br>
        <input type="submit" value="Submit">
        <input type="reset" value="Reset">
    </form>
</div>

How to add static data in dynamic table view content. And perform calculation


By : Jeff Jin
Date : March 29 2020, 07:55 AM
this will help I have one table view which will display the dynamic data of product name and its price and qty. What i need is , at last of all product showned in my table view. The total product can be any thing. Like 10 products or 2 product. What ever it may be. But at last of all product i have to show the 3 static data. Like SUBTOTAL, TAX, TOTAL. And i need to calculate the product qty X prodct cost of all product. And in my sub total, tax, totla i need to display the total amount. , Here i create one NSlayoutConstrain for tableview hight .
code :
self.tableviewhightconstrain.constant = self.tableView.contentSize.height // give value according to item


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.Addtocartdata.count == 0 {
            return 0
        }
        return self.Addtocartdata.count + 1
    }



 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row < self.Addtocartdata.count {
                let cell = tableView.dequeueReusableCell(withIdentifier: "cartcel", for: indexPath) as! cartTableViewCell
                cell.productName.text = Addtocartdata[indexPath.row].cartproName
                cell.productQty.text = Addtocartdata[indexPath.row].cartproPrice
                cell.productAmount.text = Addtocartdata[indexPath.row].cartproPrice
                return cell;
            }
            else{ // here is second cell that i create ok.
                 var total11 : Double = 0.0
                let totalitem : Int = self.Addtocartdata.count as Int
                for item in 0...totalitem - 1 {
                    let subtotal = 0.0

                   total11 = subtotal +  Double(self.Addtocartdata[item].cartproPrice!)!

                }
                print(total11)
                let totalcell = tableView.dequeueReusableCell(withIdentifier: "totalcell", for: indexPath)
                let subtotal : UILabel = totalcell.viewWithTag(5) as! UILabel

                subtotal.text = "$ \(total11)"
                let tax : UILabel = totalcell.viewWithTag(6) as! UILabel
                tax.text = "$ 125" // here give your tax 
                let finaltotal : Double = total11 + 125 // also add that text value here

                let total : UILabel = totalcell.viewWithTag(7) as! UILabel
                 total.text = "$ \(finaltotal)"

                return totalcell

            }
  }



 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row < Addtocartdata.count {
            return 70
        }else{
            return 134
        }
    }

AngularJS : table colspan rowspan dynamic calculation


By : jean
Date : March 29 2020, 07:55 AM
Any of those help I have JSON structure like below each contains Title and SubColumns. Subcolumns may or may not have extra SubCloumns.
code :
angular.module('myapp', []).controller('tableColSpanRowSpan', ['$scope', function($scope){

        $scope.finalArrayHTML = [];

        var jsonDATA = [
            {
                "Title":"Column 1",
                "SubColumns":[

                ]
            },
            {
                "Title":"Column 2",
                "SubColumns":[

                ]
            },
            {
                "Title":"Column 3",
                "SubColumns":[
                    {
                        "Title":"Column 3 : 1",
                        "SubColumns":[

                        ]
                    },
                    {
                        "Title":"Column 3 : 2",
                        "SubColumns":[
                            {
                                "Title":"Column 3 : 2 : 1",
                                "SubColumns":[

                                ]
                            },
                            {
                                "Title":"Column 3 : 2 : 2",
                                "SubColumns":[

                                ]
                            },
                            {
                                "Title":"Column 3 : 2 : 3",
                                "SubColumns":[

                                ]
                            },
                            {
                                "Title":"Column 3 : 2 : 4",
                                "SubColumns":[

                                ]
                            }
                        ]
                    },
                    {
                        "Title":"Column 3 : 3",
                        "SubColumns":[
                            {
                                "Title":"Column 3 : 3 : 1",
                                "SubColumns":[

                                ]
                            },
                            {
                                "Title":"Column 3 : 3 : 2",
                                "SubColumns":[

                                ]
                            },
                            {
                                "Title":"Column 3 : 3 : 3",
                                "SubColumns":[

                                ]
                            }
                        ]
                    }
                ]
            }
        ];

        var getColSpan = function(data, count) {
            if(data.length > 0) {
                for(var c = 0; c < data.length; c++) {
                    if(data[c].SubColumns.length > 0) {
                        count = getColSpan(data[c].SubColumns, count);
                    } else {
                        ++count;
                    }
                }

            }
            return count;
        };

        var getDepth = function (obj) {
            var depth = 0;
            if (obj.SubColumns) {
                obj.SubColumns.forEach(function (d) {
                    var tmpDepth = getDepth(d)
                    if (tmpDepth > depth) {
                        depth = tmpDepth
                    }
                })
            }
            return 1 + depth
        };

        var getRowSpan = function(allData, index, count) {
            if(allData[index].SubColumns.length > 0) {

            } else {
                var depth = 0;
                for(var j = 0; j < allData.length; j++) {
                    var depthTmp = getDepth(allData[j]);
                    if(depthTmp > depth) {
                        depth = depthTmp;
                    }
                }
                return depth;
            }
            return count;
        };

        var rowIndex = 0;
        var RecursiveFunction = function(data, currentRow) {

            for(var i = 0; i < data.length; i++) {
                var tmp = {title: data[i].Title, colSpan: getColSpan(data[i].SubColumns, 0), rowSpan: getRowSpan(data, i, 0)};
                if(typeof $scope.finalArrayHTML[rowIndex] == 'undefined') {
                    $scope.finalArrayHTML[rowIndex] = [];
                }
                $scope.finalArrayHTML[rowIndex].push(tmp);

                if(data[i].SubColumns.length > 0) {
                    ++rowIndex;
                    RecursiveFunction(data[i].SubColumns, data[i]);
                    --rowIndex;
                }
            }

        };

        RecursiveFunction(jsonDATA, 0);

    }]);
<!doctype html>
<html ng-app="myapp">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
</head>
<body>

<div ng-controller="tableColSpanRowSpan">
    <table border="1" cellspacing="2" cellpadding="3">
        <thead>
        <tr data-ng-repeat="t in finalArrayHTML">
            <th colspan="{{h.colSpan}}" rowspan="{{h.rowSpan}}" data-ng-repeat="h in t">{{h.title}}</th>
        </tr>
        </thead>
    </table>
</div>

</body>
</html>

How to do calculation in HTML table using JavaScript as I am making a dynamic invoice?


By : 10c41h0st
Date : March 29 2020, 07:55 AM
it should still fix some issue I would use .onkeyup for more responsive feedback, and then add a handler that is passed the row that you created like so:
code :
    function calculateCost(row) {
        return function () {
            row.total.value = row.cost.value * row.qty.value * row.discount.value
        }
    }

    function myfunction() {
        var table = document.getElementById("mytable");

        //adding row
        var row = table.insertRow(table.rows.length);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);
        var cell4 = row.insertCell(3);
        var cell5 = row.insertCell(4);
        var cell6 = row.insertCell(5);

        // addind rows and values
        var objInputCheckBox = document.createElement("input");
        objInputCheckBox.type = "checkbox";
        cell1.appendChild(objInputCheckBox);

        //item
        var ele2 = document.createElement('input');
        ele2.setAttribute('type', 'text');
        ele2.setAttribute('value', '');
        cell2.appendChild(ele2);

        //cost
        var ele3 = document.createElement('input');
        ele3.setAttribute('type', 'text');
        ele3.setAttribute('value', '');

        cell3.appendChild(ele3);

        //qty
        var ele4 = document.createElement('input');
        ele4.setAttribute('type', 'text');
        ele4.setAttribute('value', '');

        cell4.appendChild(ele4);

        //discount
        var ele5 = document.createElement('input');
        ele5.setAttribute('type', 'text');
        ele5.setAttribute('value', '');

        cell5.appendChild(ele5);

        //total
        var ele6 = document.createElement('input');
        ele6.setAttribute('type', 'text');
        ele6.setAttribute('value', '');
        cell6.appendChild(ele6);
        var row = {
            item: ele2,
            cost: ele3,
            qty: ele4,
            discount: ele5,
            total: ele6
        }
        var updateCostHandler = calculateCost(row);
        row.cost.onkeyup = updateCostHandler;
        row.qty.onkeyup = updateCostHandler;
        row.discount.onkeyup = updateCostHandler;
    }


    function delrow(id) {
        var table = document.getElementById(id);
        var rowcount = table.rows.length;

        for (var i = 0; i < rowcount; i++) {
            var row = table.rows[i];
            var chk = row.cells[0].childNodes[0];
            if (chk.checked) {
                table.deleteRow(i);
                rowcount--;
                i--;
            }
        }

    }
<!DOCTYPE html>
<html>
<head>
	<title>Table</title>
	<script type="text/javascript" src="js/table.js"></script>
	<style>
	table, td {
    	border: 1px solid black;
	}
</style>
</head>
<body>
	<table id="mytable">
		<tr>
			<th> </th>
			<th>Item</th>
			<th>Cost</th>
			<th>Quantity</th>
			<th>Discount</th>
			<th>Total</th>
		</tr>
	</table>
	<button onclick="myfunction()">Add</button>
	<button  onclick="delrow('mytable')">Delete</button>
	
</body>
</html>
Related Posts Related Posts :
  • How to handle state on array of checkboxes?
  • React Native - Redux ~ Props updating when not getting called
  • Fast way to add elements into an Uint8ClampedArray typed array
  • How to retrieve values from a checkbox group generated dinamically with jquery when page loads
  • Progress bar between two dates (fetch "var" from script), HTML
  • Why do Every time I start my function I get NaN
  • Angular routing change in url
  • Javascript - Change symbol on embedded tradingview script.text
  • How to select specific option?
  • Checking booleans from multiple arrays simultaneously, without multiple if statements
  • How to get a subarray?
  • Javascript JSON woes
  • Use Jquery animate to have a button move a box to the next corner
  • Why is this JavaScript not interpreted as a code block when semi-colon is used?
  • Reload another page when I click on button
  • Should functions that call a callback function be bound?
  • For loop print in single line separated by spaces - JS
  • Add Javascript Variable into asp-route-data
  • Two different POST requests are making use of the same variable
  • Convert JSOn object into a flat JSON Array
  • Manually adding to an HTML range input gives unexpected results
  • Refreshing component after making api call Reactjs
  • Google App Script : Finding The Last Blank Row
  • I cant for the life of me figure out whats wrong with this script
  • Order divs by ID in Javascript
  • set new element class property value
  • How to pass a java variable to a different jsp page containing javascript?
  • Locked it method in chai
  • React JS : history.push is not a function error and it isn't navigating to a different page onclick of swal
  • How can i set timeout for localstorage for Angular 2+?
  • Must use destructuring props assignment
  • Jest Compared values have no visual difference. when testing arrays
  • Uncaught Error: #90211 ExtensionName Error - Node.JS, Heroku, JavaScript App using FusionCharts
  • Is it possible in firebase auth to update user and custom claims at the same time node?
  • Filter out capitalized letters
  • Yet Another Google Firebase Error "Function returned undefined, expected Promise or value"
  • How do I address method in a Vue.js component from inside callback function?
  • What is the name of this feature in JavaScript?
  • Vue js using scope-slot and trying to use a property from within but having no visibility
  • Dynamic javascript table won't display iterations from array
  • How to start/end smoke.js animation by clicking a nav button?
  • Map array of strings as object properties
  • Appending new inputs with JS wipes previous ones
  • Chai Request With URL instead of JS File
  • React Jest Async Tests
  • Unordered list bullet not showing at an expected location
  • How to create an array from an object?
  • How to get prefix name from html tag
  • javascript - Simulate a click event (tap with finger) on a button in iOS
  • How to get the value of checkboxes in a kendo grid
  • Uncaught TypeError: Object(...) is not a function at eval (global-styles.js)
  • Generate divs on scroll bottom
  • App deployed to Cloud Foundry fails to start
  • Show label and percentage in Google pie chart
  • Warn user before leaving web page if changes haven't been saved
  • Objects are not valid as a React child getting error when adding div?
  • why is callback not working in nodejs with mysql?
  • D3 v4 date ticks never display last item
  • How to assign a variable which function takes as a parameter
  • Javascript how hidden div onclick of phrase
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org