簡體   English   中英

將我的 HTML 表中的兩個單元格相乘,並自動將結果與 javascript 放在第三個單元格中。 無Jquery

[英]Multiply two cells in my HTML table and automatically put the result in the third with javascript. Withot Jquery

我希望最后一列顯示“總計”,將產品數量乘以價格,並將其與產品放在同一行。

這是我的桌子的當前外觀: 在此處輸入圖像描述

這是創建表並為您提供數據的代碼。

<html>

<head>
<meta charset="utf-8" />
</head>

<style>
table,
td,
th {
    border: 1px solid black;
    border-collapse: collapse;

}
</style>

<body>

<div id="contact">

    <h1>Invoice</h1>

    <form action="/table.html">
        <label for="invoice_id">Invoice:</label>
        <input type="text" id="invoice_id" name="invoice" placeholder="Enter Invoice Id" /><br>
        <button type="button" id="form_button" value="Consultar">Consultar</button>

    </form>

</div>

<table id="demo">
    <thead>
        <tr>
            <th>Code</th>
            <th>Date</th>
            <th>Amount</th>
            <th>Barcode</th>
            <th>Name</th>
            <th>Description</th>
            <th>Price</th>
            <th id="sum">Total</th>
        </tr>
        <tr>
        </tr>
    </thead>
    <tbody id="matchData"></tbody>
</table>



</body>

<script>

let button = document.getElementById("form_button");
button.addEventListener("click", function (e) {

    let id = document.getElementById("invoice_id").value;

    let request = new XMLHttpRequest();
    request.addEventListener("load", function (e) {

        if (request.readyState == 4) {
            if (request.status == 200) {
                console.log(request.responseText); // datos de la factura
                // pasarla a objeto (JSON)



                var data = JSON.parse(request.responseText);
                //var myObj = JSON.parse(request.responseText);

                var myObj = {
                    code: data.code,
                    date: data.date,
                    lines: []

                };

                for (let i = 0; i < data.lines.length; ++i) {
                    let tmp = data.lines[i];
                    var line = {
                        amount: tmp.amount,
                        barcode: tmp.barcode,
                        name: tmp.name,
                        description: tmp.description,
                        price: tmp.price
                    };
                    myObj.lines[i] = line;
                }

                console.log(myObj);

                let table = document.getElementById('matchData'), sumVal = 0;
                let line_count = myObj["lines"].length;
                let row = document.createElement("tr");

                for (let key in myObj) {
                    if (key == "code" || key == "date") {
                        let cell = document.createElement("td");

                        cell.rowSpan = line_count;
                        cell.textContent = myObj[key];
                        row.appendChild(cell);
                    }
                    if (key == "lines") {
                        for (let line_key in myObj[key][0]) {
                            let cell = document.createElement("td");

                            cell.textContent = myObj[key][0][line_key];
                            row.appendChild(cell);



                        }
                        table.appendChild(row);

                        for (let i = 1; i < line_count; i++) {
                            let row = document.createElement("tr");

                            for (let line_key in myObj[key][i]) {
                                let cell = document.createElement("td");

                                cell.textContent = myObj[key][i][line_key];
                                row.appendChild(cell);
                            }

                            table.appendChild(row);
                        }

                    }



                }


            } else {
                console.log("Error loading page\n");
            }
        }

    });
    request.open("GET", "http://127.0.0.1:8081/invoice/" +
        id);

    request.send();

});

</script>

</html>

我一直在嘗試各種選擇,但我無法讓它發揮作用,有什么想法嗎? 謝謝。

注解:

這是你想看到的? 在此處輸入圖像描述

我希望你能這樣看:

{"code":"Fact003","date":"2021-04-19T22:00:00.000Z","lines": 
[{"amount":2,"barcode":"6854952135","name":"Teclado 
Logitech","description":"Teclado Logitech Gaming","price":45}, 
{"amount":5,"barcode":"9465986321","name":"Monitor HP 
27f","description":"Monitor de 27\" HD","price":200}, 
{"amount":3,"barcode":"5216854935","name":"Ratón 
Logitech","description":"Ratón Logitech Gaming","price":50}]}

注釋2:

這就是我的桌子現在的樣子:

在此處輸入圖像描述

我想要的是將所有產品的總和插入到下面和 TOTAL 旁邊的單元格中。 這是與舊代碼相比沒有太大變化的新代碼,但有一些變化:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>

<link rel="stylesheet" href="table.css">
</head>



<script>
function fetchID() {
    let Id = window.location.search.split('=')[1];
    loadTable(Id);
}
function loadTable(id) {

    let request = new XMLHttpRequest();
    request.addEventListener("load", function (e) {

        if (request.readyState == 4) {
            if (request.status == 200) {
                console.log(request.responseText); // datos de la factura
                // pasarla a objeto (JSON)

                var data = JSON.parse(request.responseText);

                var myObj = {
                    code: data.code,
                    date: data.date,
                    lines: []

                };

                for (let i = 0; i < data.lines.length; ++i) {
                    let tmp = data.lines[i];
                    var line = {
                        amount: tmp.amount,
                        barcode: tmp.barcode,
                        name: tmp.name,
                        description: tmp.description,
                        price: tmp.price
                    };
                    myObj.lines[i] = line;
                }

                document.getElementById("iddate").innerHTML = data.date;
                document.getElementById("idcode").innerHTML = data.code;

                console.log(myObj);

                let table = document.getElementById('matchData'),
                    sumVal = 0;
                let line_count = myObj["lines"].length;
                let row = document.createElement("tr");

                for (let key in myObj) {

                    /*if (key == "code" || key == "date") {
                        let cell = document.createElement("td");

                        cell.rowSpan = line_count;
                        cell.textContent = myObj[key];
                        row.appendChild(cell);
                    }*/

                    if (key == "lines") {

                        let price = 0,
                            amount = 0;
                        for (let line_key in myObj[key][0]) {
                            if (line_key == 'price') price = myObj[key][0][line_key];
                            if (line_key == 'amount') amount = myObj[key][0][line_key];
                            let cell = document.createElement("td");

                            cell.textContent = myObj[key][0][line_key];
                            row.appendChild(cell);
                        }

                        let cell = document.createElement("td");
                        cell.textContent = price * amount;
                        row.appendChild(cell);

                        table.appendChild(row);

                        for (let i = 1; i < line_count; i++) {
                            let row = document.createElement("tr");
                            let _price = 0,
                                _amount = 0;
                            for (let line_key in myObj[key][i]) {
                                if (line_key == 'price') _price = myObj[key][i][line_key];
                                if (line_key == 'amount') _amount = myObj[key][i][line_key];
                                let cell = document.createElement("td");

                                cell.textContent = myObj[key][i][line_key];
                                row.appendChild(cell);
                            }

                            let _cell = document.createElement("td");
                            _cell.textContent = _price * _amount;
                            row.appendChild(_cell);
                            table.appendChild(row);
                        }
                    }
                }

            } else {
                console.log("Error loading page\n");
            }
        }

    });
    request.open("GET", "http://127.0.0.1:8081/invoice/" +
        id);

    request.send();
}
</script>


<body onload="fetchID()">

<div class="date-div" id="iddate"></div>
<div id="idcode"></div>

<table id="demo">
    <thead>
        <tr>

            <th>Amount</th>
            <th>Barcode</th>
            <th>Name</th>
            <th>Description</th>
            <th>Price</th>
            <th id="sum">Total</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <td colspan="5">Total</td>
            <td></td>
        </tr>
    </tfoot>
    <tbody id="matchData"></tbody>
</table>

</body>

</html>

您可以使用querySelector()nth-child()選擇器遍歷所有行並從當前行中查找數量和價格列。

請注意,屬性id在文檔中必須是唯一的,您可以使用class代替。

演示:

 <style> table, td, th { border: 1px solid black; border-collapse: collapse; } </style> <body> <div id="contact"> <h1>Invoice</h1> <form action="/table.html"> <label for="invoice_id">Invoice:</label> <input type="text" id="invoice_id" name="invoice" placeholder="Enter Invoice Id" /><br> <button type="button" id="form_button" value="Consultar">Consultar</button> </form> </div> <table id="demo"> <thead> <tr> <th>Code</th> <th>Date</th> <th>Amount</th> <th>Barcode</th> <th>Name</th> <th>Description</th> <th>Price</th> <th id="sum">Total</th> </tr> <tr> </tr> </thead> <tbody id="matchData"> <tr> <td>Code</td> <td>Date</td> <td>2</td> <td>Barcode</td> <td>Name</td> <td>Description</td> <td>5</td> <td class="sum">Total</td> </tr> <tr> <td>Code</td> <td>Date</td> <td>2</td> <td>Barcode</td> <td>Name</td> <td>Description</td> <td>3.5</td> <td class="sum">Total</td> </tr> </tbody> </table> </body> <script> //code to calculate total var tableRow = document.querySelectorAll('#matchData tr'); tableRow.forEach(function(tr){ var amount = tr.querySelector('td:nth-child(3)').textContent; var price = tr.querySelector('td:nth-child(7)').textContent; tr.querySelector('.sum').textContent = amount * price; }); let button = document.getElementById("form_button"); button.addEventListener("click", function (e) { let id = document.getElementById("invoice_id").value; let request = new XMLHttpRequest(); request.addEventListener("load", function (e) { if (request.readyState == 4) { if (request.status == 200) { console.log(request.responseText); // datos de la factura // pasarla a objeto (JSON) var data = JSON.parse(request.responseText); //var myObj = JSON.parse(request.responseText); var myObj = { code: data.code, date: data.date, lines: [] }; for (let i = 0; i < data.lines.length; ++i) { let tmp = data.lines[i]; var line = { amount: tmp.amount, barcode: tmp.barcode, name: tmp.name, description: tmp.description, price: tmp.price }; myObj.lines[i] = line; } console.log(myObj); let table = document.getElementById('matchData'), sumVal = 0; let line_count = myObj["lines"].length; let row = document.createElement("tr"); for (let key in myObj) { if (key == "code" || key == "date") { let cell = document.createElement("td"); cell.rowSpan = line_count; cell.textContent = myObj[key]; row.appendChild(cell); } if (key == "lines") { for (let line_key in myObj[key][0]) { let cell = document.createElement("td"); cell.textContent = myObj[key][0][line_key]; row.appendChild(cell); } table.appendChild(row); for (let i = 1; i < line_count; i++) { let row = document.createElement("tr"); for (let line_key in myObj[key][i]) { let cell = document.createElement("td"); cell.textContent = myObj[key][i][line_key]; row.appendChild(cell); } table.appendChild(row); } } } } else { console.log("Error loading page\n"); } } }); request.open("GET", "http://127.0.0.1:8081/invoice/" + id); request.send(); }); </script>

Mamun的回答有效。 但是有一種更簡單的方法可以做到這一點,因為您已經在動態添加單元格。

它的關鍵是在添加價格和金額單元后創建一個額外的單元。

let price = 0, amount = 0;
for (let line_key in myObj[key][0]) {

    // Check if you are currently adding the price or amount cell and store them
    if (line_key == 'price') price = myObj[key][0][line_key];
    if (line_key == 'amount') amount = myObj[key][0][line_key];

    let cell = document.createElement("td");
    cell.textContent = myObj[key][0][line_key];
    row.appendChild(cell);
}
 
// Creating an extra column to hold the Total
let cell = document.createElement("td");
cell.textContent = price * amount;

// Add this new Total cell to the row
row.appendChild(cell);

// Then finally add the row to the table
table.appendChild(row);

因此,當您循環並添加價格和金額單元格時。 您可以將它們的值存儲在 2 個變量中,就像if (line_key == 'price') price = myObj[key][0][line_key];

然后,一旦您已經構建了所有單元格,在將行添加到表格之前,您可以使用我們的新變量創建一個新單元格,其中包含值price * amount 然后將此單元格也添加到行中,最后將行添加到表中。

之后在最后一個 for 循環中使用相同的邏輯,如下所示

for (let i = 1; i < line_count; i++) {
    let row = document.createElement("tr");
    let _price = 0, _amount = 0;
    for (let line_key in myObj[key][i]) {
        if (line_key == 'price') _price = myObj[key][i][line_key];
        if (line_key == 'amount') _amount = myObj[key][i][line_key];
        let cell = document.createElement("td");

        cell.textContent = myObj[key][i][line_key];
        row.appendChild(cell);
     }

     let _cell = document.createElement("td");
     _cell.textContent = _price * _amount;
     row.appendChild(_cell);
     table.appendChild(row);
 }

如果您想通過 go 添加代碼片段

 <html> <head> <meta charset="utf-8" /> </head> <style> table, td, th { border: 1px solid black; border-collapse: collapse; } </style> <body> <div id="contact"> <h1>Invoice</h1> <form action="/table.html"> <label for="invoice_id">Invoice:</label> <input type="text" id="invoice_id" name="invoice" placeholder="Enter Invoice Id" /><br> <button type="button" id="form_button" value="Consultar">Consultar</button> </form> </div> <table id="demo"> <thead> <tr> <th>Code</th> <th>Date</th> <th>Amount</th> <th>Barcode</th> <th>Name</th> <th>Description</th> <th>Price</th> <th id="sum">Total</th> </tr> <tr> </tr> </thead> <tbody id="matchData"></tbody> </table> </body> <script> let button = document.getElementById("form_button"); button.addEventListener("click", function(e) { let id = document.getElementById("invoice_id").value; // let request = new XMLHttpRequest(); // request.addEventListener("load", function (e) { if (true) { if (true) { // console.log(request.responseText); // datos de la factura // pasarla a objeto (JSON) const data = { "code": "Fact003", "date": "2021-04-19T22:00:00.000Z", "lines": [{ "amount": 2, "barcode": "6854952135", "name": "Teclado Logitech", "description": "Teclado Logitech Gaming", "price": 45 }, { "amount": 5, "barcode": "9465986321", "name": "Monitor HP 27f", "description": "Monitor de 27\" HD", "price": 200 }, { "amount": 3, "barcode": "5216854935", "name": "Ratón Logitech", "description": "Ratón Logitech Gaming", "price": 50 } ] }; var myObj = { code: data.code, date: data.date, lines: [] }; for (let i = 0; i < data.lines.length; ++i) { let tmp = data.lines[i]; var line = { amount: tmp.amount, barcode: tmp.barcode, name: tmp.name, description: tmp.description, price: tmp.price }; myObj.lines[i] = line; } console.log(myObj); let table = document.getElementById('matchData'), sumVal = 0; let line_count = myObj["lines"].length; let row = document.createElement("tr"); for (let key in myObj) { if (key == "code" || key == "date") { let cell = document.createElement("td"); cell.rowSpan = line_count; cell.textContent = myObj[key]; row.appendChild(cell); } if (key == "lines") { let price = 0, amount = 0; for (let line_key in myObj[key][0]) { if (line_key == 'price') price = myObj[key][0][line_key]; if (line_key == 'amount') amount = myObj[key][0][line_key]; let cell = document.createElement("td"); cell.textContent = myObj[key][0][line_key]; row.appendChild(cell); } let cell = document.createElement("td"); cell.textContent = price * amount; row.appendChild(cell); table.appendChild(row); for (let i = 1; i < line_count; i++) { let row = document.createElement("tr"); let _price = 0, _amount = 0; for (let line_key in myObj[key][i]) { if (line_key == 'price') _price = myObj[key][i][line_key]; if (line_key == 'amount') _amount = myObj[key][i][line_key]; let cell = document.createElement("td"); cell.textContent = myObj[key][i][line_key]; row.appendChild(cell); } let _cell = document.createElement("td"); _cell.textContent = _price * _amount; row.appendChild(_cell); table.appendChild(row); } } } } else { console.log("Error loading page\n"); } } // }); // request.open("GET", "http://127.0.0.1:8081/invoice/" + // id); // request.send(); }); </script> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM