jquery动态添加文本框的总和

时间:2013-12-10 15:02:26

标签: javascript jquery

我有一个页面,我可以使用带有'prijs'类的文本框添加和删除行。当页面加载时,已经有一行。

现在我需要将所有文本框的值与类'prijs'相加,并将其显示在ID为'totaalexbtw'的TD中。这是我的问题:它不会循环添加的文本框。此外,当删除文本框时,总数应该受到影响。

非常感谢一些帮助!!我被困了好几天了!

提前致谢!

<html>
<head>
    <script type="text/javascript" src="javascript/jquery_v2.0.3.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        function kiesklant(str)
        {
            var xmlhttp;
            if (str=="")
            {
                document.getElementById("klantinfo").innerHTML="<table><tr><td>Naam:</td><td</td></tr><td>Adres:</td><td></td></tr><td>Tel:</td><td></td></tr>";
                return;
            }

            if (window.XMLHttpRequest)
            {
                xmlhttp = new XMLHttpRequest();
            }
            else
            {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }

            xmlhttp.onreadystatechange = function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("klantinfo").innerHTML = xmlhttp.responseText;
                }
            }

            xmlhttp.open("GET", "kiesklant.php?q="+str, true);
            xmlhttp.send();
        };


        var linenumber = 0;
        function addLine()
        {
            linenumber++;
            var newRow = document.createElement('tr');
            var newCell = document.createElement('td');

            newCell = document.createElement('td');
            var inputNode = document.createElement('input');
            inputNode.name = 'dienstomschrijving';
            inputNode.setAttribute('type', 'text');
            inputNode.setAttribute('style', 'width: 200px');
            newCell.appendChild(inputNode);
            newRow.appendChild(newCell);

            newCell = document.createElement('td');
            inputNode = document.createElement('input');
            inputNode.name = 'prijs';
            inputNode.setAttribute('type', 'text');
            inputNode.setAttribute('style', 'width: 100px');
            inputNode.className = 'prijs';
            newCell.appendChild(inputNode);
            newRow.appendChild(newCell);

            newCell = document.createElement('td');
            inputNode = document.createElement('input');
            inputNode.name = 'verwijder_dienst';
            inputNode.setAttribute('type', 'button');
            inputNode.setAttribute('onclick', 'delLine(this)');
            inputNode.value = 'Verwijder dienst';

            newCell.appendChild(inputNode);
            newRow.appendChild(newCell);

            document.getElementById('dienst').appendChild(newRow);
        };

        function delLine(line)
        {
            var row = line.parentNode.parentNode;
            row.parentNode.removeChild(row);
        };


        function bereken()
        {
            var sumexbtw = $('.prijs').sum(function()
            {
                return +parseFloat(this.value) || 0;
            });

            $('#totaalexbtw').val(sumexbtw.toFixed(2));

            var btw = sumexbtw * 0,21;

            $('#btw').val(btw.toFixed(2));

            var totaal = sumexbtw + btw;

            $('#totaal').val(totaal.toFixed(2));
        };

        $(document).on('change', 'input.prijs', bereken);

    </script>
</head>
<body>
    <?php
        include("function.php");

        // haal max factuurnr op uit database
        $sth1 = maakConnectie() -> prepare("SELECT MAX(factuurnummer) as 'max' FROM factuur");
        $sth1 -> execute();
        $result = $sth1 -> fetchAll(PDO :: FETCH_ASSOC);

        // tel hier 1 bij op zodat er steeds opeenvolgende nummers worden genereerd
        foreach($result as $rij)
        {
            $factuurnr = $rij['max'] + 1;
        }

        $datum = date("d-m-Y");

        $sth2 = maakConnectie() -> prepare("SELECT voornaam, achternaam FROM gebruiker");
        $sth2 -> execute();
        $result2 = $sth2 -> fetchAll (PDO::FETCH_ASSOC);
    ?>


    <form method="GET" action="aanmaken_factuur.php" class="formulier">
        <table>
            <tr>
                <td>Factuur nr:</td>
                <td align="right"><?php print($factuurnr);?></td>
            </tr>
            <tr>
                <td>Datum:</td>
                <td align="right"><?php print($datum);?></td>
            </tr>
        </table>
        <br>
        <table>
            <tr>
                <td><select name="klanten" onchange="kiesklant(this.value)">
                        <option value="" selected>Kies klant</option>
                        <?php foreach($result2 as $rij)
                        {
                            print("<option value=\"".$rij["voornaam"]." ".$rij["achternaam"]."\">".$rij["voornaam"]." ".$rij["achternaam"]."</option>");
                        }?>
                    </select>
                </td>
            </tr>
        </table>
        <div id="klantinfo">
            <table>
                <tr>
                    <td>Naam:</td>
                    <td></td>
                </tr>
                <tr>
                    <td>Adres:</td>
                    <td></td>
                </tr>
                <tr>
                    <td>Tel:</td>
                    <td></td>
                </tr>
            </table>
        </div>
        <br>
        <table id="dienst2">
            <tbody id="dienst">
                <tr>
                    <th align="left">Dienstomschrijving</th>
                    <th align="left">Prijs</th>
                </tr>
                <tr>
                    <td><input style="width: 200px" type="text" name="dienstomschrijving"></td>
                    <td><input style="width: 100px" type="text" name="prijs" class="prijs"></td>
                    <td><input type="button" name="verwijder_dienst" value="Verwijder dienst" onclick="delLine(this);"/></td>
                </tr>
            </tbody>
                <tr>
                    <td><input type="button" name="toevoegen_dienst" value="Voeg dienst toe" onclick="addLine();" /></td>
                </tr>
        </table><br>
        <table id="totaal">
            <tr>
                <td align="right">Totaal excl. BTW</td>
                <td align="center" id="totaalexbtw"></td>
            </tr>
            <tr>
                <td align="right">BTW 21%</td>
                <td align="center" id="btw"></td>
            </tr>
            <tr>
                <td colspan=2 align="center">_________________________________________</td>
            </tr>
            <tr>
                <td align="right">Factuur totaal</td>
                <td align="center" id="totaal"></td>
            </tr>
            <tr>
                <td align="right"><button onclick="index2.php" name="annuleren">Annuleren</button></td>
                <td align="right"><input type="submit" name="submit" value="Maak factuur aan"></td>
            </tr>
        </table>
    </form>

2 个答案:

答案 0 :(得分:6)

您的代码中有两个错误

$('.prijs').each.change(berekentotaalexbtw());
            ^^^^                          ^^ 

不需要使用每个,你没有分配这个功能,你正在调用它。

$('.prijs').change(berekentotaalexbtw);

答案 1 :(得分:1)

因为昨天我做了同样的事情:

(function($) {
    $.fn.sum = function (callback) {
        var sum = 0;
        this.each(function () {
            sum += 1 * callback.apply(this);
        });
        return sum;
    };
})(jQuery);

这只是一个辅助函数函数,所以你可以这样做:$('。prijs')。sum(....);而不是使用.each(....)

这是你的答案

// If you do $('.prijs').change() it binds it to the currently existing elements.
// i think you are adding and deleting them dynamically, so you needed a delegated event.
function berekentotaalexbtw() {
    var sum = $('.prijs').sum(function() {
        // just a shorter version of all the 'isNan' stuff you got going on.
        // defaults to 0 if it's NaN
        return +parseFloat(this.value) || 0;
    });
    // Since you want it printed like a currency: use sum.toFixed(2) to format it :-)
    $('#totaalexbtw').val( sum.toFixed(2) );
}
$(document).on('change','input.prijs',berekentotaalexbtw);
// and on deletion of an element: berekentotaalexbtw();