开发者

Loop on ID and each function

开发者 https://www.devze.com 2023-02-19 22:03 出处:网络
I use the JQUERY EACH function to SUM dynamically 12 textbox values with a \"txt\" class with this code :

I use the JQUERY EACH function to SUM dynamically 12 textbox values with a "txt" class with this code :

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

        //iterate through each textboxes and add ke开发者_运维百科yup
        //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);
                }

        });

        $("#sum").html(sum);
</script>

I want to create 4 subtotals computed dynamically using each only 3 textbox values. I added 4 different ID to each in my form. How can i use the function above to compute dynamically the subtotal for the current id. The spans id which gets the result are named "ID_SUM" (ID must be dynamic according to the ID value of the textbox modified) ?? Thank u very much.


i found a solution... ID is unique so it doesn't work. i used the name attribute like this :

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

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

            $(this).keyup(function(){
            calculateSum($(this).attr("name"));
            });
        });

    });

    function calculateSum(groupe) {

        var sum = 0;
        var subtotal = 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))
        $("#sum").html(sum);

        $('input[name="' + groupe + '"]').each(function() {

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

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

    }
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号