JavaScript - 将新字段添加到现有字段

时间:2014-04-16 15:47:03

标签: javascript html

我正在努力完成这项功课 试图继续添加用户将添加的新2字段的乘法。

示例:

  

第一场5秒场5 =总数是5 * 5 = 25

但是当用户点击添加字段时,他会:

  

第一场= 5秒场5   第一场= 6秒场6总计将是5 * 5 + 6 * 6 = 61等等

<script>
    function calc(form) {
        var box1 = parseFloat (form.leftover.value,10)
        var box2 = parseFloat (form.charge.value,10)

        var temp = new Array();
        var Mbalance = ( box1 * box2 ) ; 
        temp.push(Mbalance) ; 

        for ( var i=0; i< temp.length ; i++ ) {
            Mbalance = Mbalance+Mbalance ; 
        }

        form.mbalance.value= Mbalance ; 
    }

    // This script is identical to the above JavaScript function.

    var ct = 1;

    function new_link(form) {
        ct++ ; 
        var div1 = document.createElement('div');
        div1.id = ct;
        // Link to delete extended form elements
        div1.innerHTML = document.getElementById('newlinktpl').innerHTML ;
        document.getElementById('newlink').appendChild(div1);
    }

</script>
</script>

<form> 
<div id="newlink">
<div>
    <td width="423">What was the balance left over from last month ?</td>
    <td width="19">$</td>
    <td width="141"><input  name="leftover" value="" maxlength="10" /></td>
    </tr>
    <tr>
    <td>How much did you charge this month ?</td>
    <td>$</td>
    <td><input  name="charge" value="" maxlength="10" /></td>
    <br/>
    </div></div>
    <button type="submit" id="buttoncalculate"  onclick="calc(this.form); return false; "></button>
    <br />
    <td width="462">Monthly Balance</td>
    <td width="128"><input  name="mbalance" value="" maxlength="10" /></td>
    <a href="javascript:new_link()">Add new </a>
</form>
<form>
    <!-- Template -->
    <div id="newlinktpl" style="display:none">
        <div>
            <td width="423">What was the balance left over from last month ?</td>
            <td width="19">$</td>
            <td width="141"><input  name="leftover" value="" maxlength="10" /></td>
            </tr>
            <tr>
            <td>How much did you charge this month ?</td>
            <td>$</td>
            <td><input  name="charge" value="" maxlength="10" /></td>
        </div>
    </div>
<form>

1 个答案:

答案 0 :(得分:0)

这是你可以做到的一种方式。它不一定是最好的,但它实现了你想要的东西,我不觉得完全重写你所拥有的:

http://jsfiddle.net/HS6dt/2/

我在两个输入的父div和两个输入中添加了一个类。这样我就可以找到父div,然后找到后代输入,获取它们的值并将它们多个(注意:我不知道你为什么要将这两个值相乘,它实际上没有多大意义,但无论如何):< / p>

function calc(form) {
    var total = 0;
    var items = document.getElementsByClassName("item");

    for (var i = 0; i < items.length; i++) {
        var left = items[i].getElementsByClassName("leftover");
        var charge = items[i].getElementsByClassName("charge");
        total += parseFloat(left[0].value, 10) * parseFloat(charge[0].value, 10);
    }
    form.mbalance.value = total;
}