简体   繁体   English

如何在不为每个输入使用不同 id 标签的情况下使用 for 循环?

[英]How to use a for loop without using different id tags for each input?

How to use a for loop without using different id tags for each input?如何在不为每个输入使用不同 id 标签的情况下使用 for 循环? The result for the javascript works however I want to know how to use for loop so I do not have to change every id tags in order to achieve the same result. javascript 的结果有效,但是我想知道如何使用 for 循环,因此我不必更改每个 id 标签即可获得相同的结果。

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <link href="https://fonts.googleapis.com/css2?family=Lobster&family=Pathway+Gothic+One&display=swap" rel="stylesheet"> <title>Book Ordering System</title> <style> body{ background-image: linear-gradient(to right,#FF7F50,#008080); } thead, tfoot { background-color: skyblue; } tbody td:nth-child(5) input, tbody td:nth-child(6) input, tbody td:nth-child(7) input { text-align: right; } tr:hover { background-color: yellow; } td:last-of-type input { background-color: silver; } tfoot, tfoot input { text-align: right; } tfoot td:last-of-type input { font-size: 18pt; } table{ border-style: dashed; border-width: medium; border-color: #EEE8AA; } tbody td:nth-child(5) input, tbody td:nth-child(6) input{ background-color: tomato; } tbody td:nth-child(2) input{ background-color: #00FF7F; } tbody td:nth-child(3) input{ background-color: #EE82EE; } tbody td > select{ background-color: #FFA500; } table:active { background-color: green; } h1{ font-family: 'Lobster', cursive; } thead th{ font-family: 'Pathway Gothic One', sans-serif; color: #CD5C5C; } </style> </head> <body> <h1>Book Ordering System</h1> <form method="post"> <table border="2"> <thead> <tr> <th>No.</th> <th>Book Title</th> <th>Author</th> <th>Category</th> <th>Unit Price</th> <th>Quantity</th> <th>Total</th> </tr> </thead> <tfoot> <tr> <td colspan="5"> <input type="button" onclick="calculateTotal();" value="Calculate Grand Total Price"> </td> <td colspan="2"> <input type="text" name="grandTotal" id="grandTotal" value="0.00" readonly="readonly"> </td> </tr> </tfoot> <tbody> <tr> <td>1</td> <td> <label for="sec1"></label> <input type="text" name="sec1" id="sec1" value="" /> </td> <td> <label for="sec2"></label> <input type="text" name="sec2" id="sec2" value="" /> </td> <td> <select name="category" id="category"> <option value="choose">Please choose the category...</option> <option value="biz">Business</option> <option value="fiction">Fiction</option> <option value="maths">Mathematics</option> <option value="tech">Technology</option> </select> </td> <td> <label for="sec3"></label> <input type="text" name="sec3" id="sec3" value="0.00" /> </td> <td> <label for="sec4"></label> <input type="text" name="sec4" id="sec4" value="0" /> </td> <td> <label for="sec5"></label> <input type="text" name="sec5" id="sec5" value="0.00" readonly="readonly" /> </td> </tr> <tr> <td>2</td> <td> <label for="sec1"></label> <input type="text" name="sec6" id="sec6" value="" /> </td> <td> <label for="sec2"></label> <input type="text" name="sec7" id="sec7" value="" /> </td> <td> <select name="category" id="category"> <option value="choose">Please choose the category...</option> <option value="biz">Business</option> <option value="fiction">Fiction</option> <option value="maths">Mathematics</option> <option value="tech">Technology</option> </select> </td> <td> <label for="sec3"></label> <input type="text" name="sec8" id="sec8" value="0.00" /> </td> <td> <label for="sec4"></label> <input type="text" name="sec9" id="sec9" value="0" /> </td> <td> <label for="sec5"></label> <input type="text" name="sec10" id="sec10" value="0.00" readonly="readonly" /> </td> </tr> <tr> <td>3</td> <td> <label for="sec1"></label> <input type="text" name="sec11" id="sec11" value="" /> </td> <td> <label for="sec2"></label> <input type="text" name="sec12" id="sec12" value="" /> </td> <td> <select name="category" id="category"> <option value="choose">Please choose the category...</option> <option value="biz">Business</option> <option value="fiction">Fiction</option> <option value="maths">Mathematics</option> <option value="tech">Technology</option> </select> </td> <td> <label for="sec3"></label> <input type="text" name="sec13" id="sec13" value="0.00" /> </td> <td> <label for="sec4"></label> <input type="text" name="sec14" id="sec14" value="0" /> </td> <td> <label for="sec5"></label> <input type="text" name="sec15" id="sec15" value="0.00" readonly="readonly" /> </td> </tr> <tr> <td>4</td> <td> <label for="sec1"></label> <input type="text" name="sec16" id="sec16" value="" /> </td> <td> <label for="sec2"></label> <input type="text" name="sec17" id="sec17" value="" /> </td> <td> <select name="category" id="category"> <option value="choose">Please choose the category...</option> <option value="biz">Business</option> <option value="fiction">Fiction</option> <option value="maths">Mathematics</option> <option value="tech">Technology</option> </select> </td> <td> <label for="sec3"></label> <input type="text" name="sec18" id="sec18" value="0.00" /> </td> <td> <label for="sec4"></label> <input type="text" name="sec19" id="sec19" value="0" /> </td> <td> <label for="sec5"></label> <input type="text" name="sec20" id="sec20" value="0.00" readonly="readonly" /> </td> </tr> <tr> <td>5</td> <td> <label for="sec1"></label> <input type="text" name="sec21" id="sec21" value="" /> </td> <td> <label for="sec2"></label> <input type="text" name="sec22" id="sec22" value="" /> </td> <td> <select name="category" id="category"> <option value="choose">Please choose the category...</option> <option value="biz">Business</option> <option value="fiction">Fiction</option> <option value="maths">Mathematics</option> <option value="tech">Technology</option> </select> </td> <td> <label for="sec3"></label> <input type="text" name="sec23" id="sec23" value="0.00" /> </td> <td> <label for="sec4"></label> <input type="text" name="sec24" id="sec24" value="0" /> </td> <td> <label for="sec5"></label> <input type="text" name="sec25" id="sec25" value="0.00" readonly="readonly" /> </td> </tr> </tbody> </table> </form> <script> function calculateTotal(){ let total = 0; let num1 = document.getElementById("sec3").value ; let num2 = document.getElementById("sec4").value ; document.getElementById("sec5").value = (num1 * num2).toFixed(2); total += (num1 * num2); num1 = document.getElementById("sec8").value ; num2 = document.getElementById("sec9").value ; document.getElementById("sec10").value = (num1 * num2).toFixed(2); total += (num1 * num2); num1 = document.getElementById("sec13").value ; num2 = document.getElementById("sec14").value ; document.getElementById("sec15").value = (num1 * num2).toFixed(2); total += (num1 * num2); num1 = document.getElementById("sec18").value ; num2 = document.getElementById("sec19").value ; document.getElementById("sec20").value = (num1 * num2).toFixed(2); total += (num1 * num2); num1 = document.getElementById("sec23").value ; num2 = document.getElementById("sec24").value ; document.getElementById("sec25").value = (num1 * num2).toFixed(2); total += (num1 * num2); document.getElementById("grandTotal").value = total.toFixed(2); } </script> </body> </html>

How to use a for loop without using different id tags for each input?如何在不为每个输入使用不同 id 标签的情况下使用 for 循环? The result for the javascript works however I want to know how to use for loop so I do not have to change every id tags in order to achieve the same result. javascript 的结果有效,但是我想知道如何使用 for 循环,因此我不必更改每个 id 标签即可获得相同的结果。

I would like to suggest, use class to get element instead of IDs.我想建议,使用类来获取元素而不是 ID。 Assign class to each column as below:为每一列分配类,如下所示:

                       <td>
                            <label for="sec3"></label>
                            <input type="text" name="sec3" id="sec3" class="unit-price" value="0.00" />
                        </td>
                        <td>
                            <label for="sec4"></label>
                            <input type="text" name="sec4" id="sec4" class="units" value="0" />
                        </td>
                        <td>
                            <label for="sec5"></label>
                            <input type="text" name="sec5" id="sec5" value="0.00" class="total-units-price" readonly="readonly" />
                        </td>

Then try below JS code:然后尝试下面的JS代码:

<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
  crossorigin="anonymous"></script>
        <script>
            function calculateTotal() {

                let total = 0;

                $('tbody tr').each(function(){
                    let unit_price = $(this).find('.unit-price').val();
                    let units = $(this).find('.units').val();
                    let total_units_price = Number.parseFloat(unit_price) * units;
                    total_units_price = Number.parseFloat(total_units_price).toFixed(2);
                    $(this).find('.total-units-price').val(total_units_price);
                    total += total_units_price;

                })
                total = Number.parseFloat(total).toFixed(2);
                document.getElementById("grandTotal").value = total;
            }
            
        </script>

If you don't want to use Jquery at all here is pure javascript snippet for you:如果您根本不想使用 Jquery,这里有纯 javascript 片段供您使用:

<script>
    function calculateTotal() {
        let total = 0;
        let rows = document.getElementsByTagName('tbody')[0].getElementsByTagName('tr');

        for (i = 0; i < rows.length; i++){
            let unit_price = rows[i].getElementsByClassName('unit-price')[0].value;
            let units = rows[i].getElementsByClassName('units')[0].value;

            let total_units_price = Number.parseFloat(unit_price) * units;
            total_units_price = Number.parseFloat(total_units_price).toFixed(2);

            rows[i].getElementsByClassName('total-units-price')[0].value = total_units_price;
            
            total =  Number.parseFloat(total) + Number.parseFloat(total_units_price);
        }
        document.getElementById("grandTotal").value = total.toFixed(2);
    }
</script>

Note: You have to putt this script in <head> section to resolve the error: test.html:101 Uncaught ReferenceError: calculateTotal is not defined注意:您必须将此脚本放在<head>部分以解决错误: test.html:101 Uncaught ReferenceError: calculateTotal is not defined

Or bind function with click event like:或使用单击事件绑定函数,例如:

$('button').on('click', calculateTotal());

Hope you got it now and it works for you.希望你现在明白了,它对你有用。 Let me know if still facing any problem.如果仍然面临任何问题,请告诉我。

It is better to assign a class name for this kind of task, so replace the IDs with a class name so u can access them all at once最好为此类任务分配一个类名,因此将 ID 替换为类名,以便您可以一次访问它们

check this code检查此代码

<body>
    <td>
        <label for="sec3"></label>
        <input type="text" name="sec3" class="sec3" value="0.00" />
    </td>
    <td>
        <label for="sec4"></label>
        <input type="text" name="sec4" class="sec4" value="0" />
    </td>
    <td>
        <label for="sec5"></label>
        <input type="text" name="sec5" class="sec5" value="0.00" readonly="readonly" />
    </td>

    <script>
        function calculateTotal(){
            let total = 0;
            let num1 = document.querySelectorAll(".sec3");
            let num2 = document.querySelectorAll(".sec4");
            let tot = document.querySelectorAll(".sec5");

            for(uPrice of num1){
                for(q of num2){
                    for(t of tot){
                        t.value = (uPrice.value * q.value).toFixed(2);
                        total += t.value;
                    }
                }
            }
        }
        calculateTotal();
    </script>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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