对动态添加的行执行计算 [英] Perform calculations on dynamically added rows

查看:46
本文介绍了对动态添加的行执行计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的表单通过使用Javascript将价格和数量值相乘来计算总数,并自动在总输入框中显示该值。

Below form calculates the total by multiplying the price and quantity values using Javascript and shows that value in the Total 'input box' automatically.

<html> 
<script>
    function calculate() {
    var myBox1 = document.getElementById('qty').value;  
    var myBox2 = document.getElementById('price').value;
    var myResult1 = myBox1 * myBox2;
    total.value = myResult1;

    }       
</script> 
<body>
<p> 

           <table id="dataTable" class="form" border="1">
              <tbody>
                <tr>
                  <p>
                  <td>
                        <label>Quantity</label>
                        <input type="text" required="required" name="qty" id="qty" oninput="calculate()">
                     </td>
                     <td>
                        <label for="price">Price</label>
                        <input type="text" required="required" class="small"  name="price" id="price" oninput="calculate()">
                     </td>
                     <td>
                        <label for="total">Total</label>
                        <input type="text" required="required" class="small"  name="total" id="total">

                     </td>
                     <td>

                     </td>
                        </p>
                </tr>
                </tbody>
            </table>
</body>
</html>

现在添加了一个'添加/删除'选项(使用Javascript),如下所示添加/删除行到形式,仍然希望像以前一样对每个单独的行进行计算。请帮我解决这个问题。

Now added a 'Add/Remove' option (using Javascript) like shown below which adds/removes rows to the form and still want the calculation to take place for each individual row like previously. Please help me out as am new to this.

<html>
<script>
function addRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    if(rowCount < 4){                           // limit the user from creating fields more than your limits
        var row = table.insertRow(rowCount);
        var colCount = table.rows[0].cells.length;
        for(var i=0; i<colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[0].cells[i].innerHTML;
        }
    }else{
         alert("Maximum Passenger per ticket is 4.");

    }
}

function deleteRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    for(var i=0; i<rowCount; i++) {
        var row = table.rows[i];
        var chkbox = row.cells[0].childNodes[0];
        if(null != chkbox && true == chkbox.checked) {
            if(rowCount <= 1) {                         // limit the user from removing all the fields
                alert("Cannot Remove all the Passenger.");
                break;
            }
            table.deleteRow(i);
            rowCount--;
            i--;
        }
    }
}

function calculate() {
        var myBox1 = document.getElementById('qty').value;  
        var myBox2 = document.getElementById('price').value;
        var myResult1 = myBox1 * myBox2;
        total.value = myResult1;

    }       
</script> 
<body>
<p> 
                <input type="button" value="Add" onClick="addRow('dataTable')" /> 
                <input type="button" value="Remove" onClick="deleteRow('dataTable')"  /> 

           <table id="dataTable" class="form" border="1">
              <tbody>
                <tr>
                  <p>
                  <td>
                        <label>Quantity</label>
                        <input type="text" required="required" name="qty" id="qty" oninput="calculate()">
                     </td>
                     <td>
                        <label for="price">Price</label>
                        <input type="text" required="required" class="small"  name="price" id="price" oninput="calculate()">
                     </td>
                     <td>
                        <label for="total">Total</label>
                        <input type="text" required="required" class="small"  name="total" id="total">

                     </td>
                    </p>
                </tr>
                </tbody>
            </table
</body>
</html>

PS:虽然我能找到两个与此类似的帖子,但我无法实现这些解决方案由于我对Javascript的了解有限。只是在徒劳地找到过去一周左右的解决方案之后才创建了这篇文章。

P.S: Though I was able to find two posts similar to this one, am unable to implement those solutions due to my limited knowledge of Javascript. Only created this post after trying in vain to find a solution for the past one week or so.

推荐答案

这很难用纯java脚本实现。
真的建议学习jQuery和/或AngularJS会让你的生活更轻松。

This is hard to achieve with pure java-script however possible. It is really recommended to learn jQuery and/or AngularJS will make your life much easier.

基本上你需要添加行并给它们唯一的ID,然后使用每个单元格计算方法及其自己的行ID。

Basically you need to add rows and give them unique ID, then use each cell calculate method with its own row ID.

新的HTML如下所示:(注意我已从单元格中删除了ID,因为我将使用'name 'property)(页面上只允许一个唯一ID)

The new HTML looks like this: (notice I've removed the ID from the cells cause I will use 'name' property) (only one unique ID is allowed on page)

<input type="button" value="Add" onClick="addRow('dataTable')" />
<input type="button" value="Remove" onClick="deleteRow('dataTable')" />
<table id="dataTable" class="form" border="1">
    <tbody>
        <tr id='row_0'>
            <p>
                <td>
                    <label>Quantity</label>
                    <input type="text" required="required" name="qty" oninput="calculate('row_0')">
                </td>
                <td>
                    <label for="price">Price</label>
                    <input type="text" required="required" class="small" name="price" oninput="calculate('row_0')">
                </td>
                <td>
                    <label for="total">Total</label>
                    <input type="text" required="required" class="small" name="total">
                </td>
            </p>
        </tr>
    </tbody>
</table>

JS:

function addRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    if (rowCount < 4) { // limit the user from creating fields more than your limits
        var row = table.insertRow(rowCount);

        var colCount = table.rows[0].cells.length;
        row.id = 'row_'+rowCount;
        for (var i = 0; i < colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.outerHTML = table.rows[0].cells[i].outerHTML;            
        }
       var listitems= row.getElementsByTagName("input")
            for (i=0; i<listitems.length; i++) {
              listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
            }
    } else {
        alert("Maximum Passenger per ticket is 4.");

    }
}

function deleteRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    for (var i = 0; i < rowCount; i++) {
        var row = table.rows[i];
        var chkbox = row.cells[0].childNodes[0];
        if (null !== chkbox && true === chkbox.checked) {
            if (rowCount <= 1) { // limit the user from removing all the fields
                alert("Cannot Remove all the Passenger.");
                break;
            }
            table.deleteRow(i);
            rowCount--;
            i--;
        }
    }
}

function calculate(elementID) {
    var mainRow = document.getElementById(elementID);
    var myBox1 = mainRow.querySelectorAll('[name=qty]')[0].value;
    var myBox2 = mainRow.querySelectorAll('[name=price]')[0].value;
    var total = mainRow.querySelectorAll('[name=total]')[0];
    var myResult1 = myBox1 * myBox2;
    total.value = myResult1;

}

工作示例(小提琴)

PS:旧浏览器不支持函数querySelector。 (我在镀铬上测试过它)

PS: the function querySelector is not supported on older browsers. (I've tested it on chrome)

这篇关于对动态添加的行执行计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆