0

我使用 java 脚本添加了多个文本框值.. 像多个价格.. 我想计算总价这是我的脚本 fo 自动生成文本框 $(document).ready(function(){

    //iterate through each textboxes and add keyup
    //handler to trigger sum event
    $(".txt").each(function() {

        $(this).keyup(function(){
            calculateSum();
        });
    });

});

function calculateSum() {


enter code here
    var sum = 0;
    //iterate through each textboxes and add the values
    $(".txt").each(function() {

        //add only if the value is number
        if(!isNaN(this.value) && this.value.length!=0) {
            sum += parseFloat(this.value);
        }

    });
    //.toFixed() method will roundoff the final sum to 2 decimal places
    $("#sum").html(sum.toFixed(2));
}

我有html代码

    <th>Description</th>           
    <th>Code</th>
    <th>Qty</th>
    </tr>
    <tr id="Row2">
        <th width="300">
            <input type="text" name="desc" size="43" />
        </th>
        <th>
            <input type="text" name="code" />
        </th>
        <th>
           <input type="text"  name="qty" size="10"  class="txt"/>
        </th>

    </tr>
</table>
                               Total Qty:<span id="sum">0</span><input type="hidden" name="totalqty" align="right" id="sum" size="10" >
<button type="button" id="btnAdd">Add few more Rows!</button>

我有添加脚本的代码

<script>
    $(document).ready(function(){

        //iterate through each textboxes and add keyup
        //handler to trigger sum event
        $(".txt").each(function() {

            $(this).keyup(function(){
                calculateSum();
            });
        });

    });

    function calculateSum() {

        var sum = 0;
        //iterate through each textboxes and add the values
        $(".txt").each(function() {

            //add only if the value is number
            if(!isNaN(this.value) && this.value.length!=0) {
                sum += parseFloat(this.value);
            }

        });
        //.toFixed() method will roundoff the final sum to 2 decimal places
        $("#sum").html(sum.toFixed(2));
    }
</script>
4

1 回答 1

1

每个函数接受两个参数

$(".txt").each(function(index, htmlElement){
    $(htmlElement).keyup(function(event){
        //do your code here
        calculateSum();
    })
});

你的 calculateSum 将是这样的

function calculateSum(){
    $(".txt").each(function(index, htmlElement){
        sum += parseFloat($(htmlElement).val());
    });
}

每个函数中回调函数的第一个参数是所选元素数组中元素的索引号

第二个参数是选定元素数组(html 输入元素)中的当前选定元素。

于 2013-11-08T10:23:04.153 回答