对动态添加的行执行计算

时间:2015-07-17 07:13:23

标签: javascript

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

<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),如下所示,它向表单添加/删除行,并且仍然希望像以前一样对每个单独的行进行计算。请帮我解决这个问题。

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

1 个答案:

答案 0 :(得分:1)

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

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

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

<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;

}

Working example (fiddle)

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