开发者

I have a dynamic form with lines addes to the dom with jquery, and the total price seems to be acting strangly

开发者 https://www.devze.com 2022-12-22 04:33 出处:网络
I can add and remove the last line in my dynamic form and calculate the sum of the unit prices but the calculateSumNoTax() function seems to only be fired bu the first line which is output by php, eve

I can add and remove the last line in my dynamic form and calculate the sum of the unit prices but the calculateSumNoTax() function seems to only be fired bu the first line which is output by php, every other line appended to the dom via jquery dont fire calculateSumNoTax();

What am I doing wrong here ?

JS :

$(document).ready(function() {
        $("a[name='addline']").click(function(){
            $("input[name='counter']").val( Number($("input[name='counter']").val()) + 1 );
            var i = $("input[name='counter']").val();
            $('#quote > tbody:last').append('<tr id="row'+i+'"><td>'+i+'</td><td><input type="text" name="description_'+i+'" value=""  /></td><td><input type="text" name="quantity_'+i+'" value="1"  /></td><td><input type="text" name="unit_price_'+i+'" class="unit_price" value=""  /></td><td><select name="tax_percentage_'+i+'"><option value="0" selected="selected">0</option><option value="19.6">19.6%</option></select></td></tr>');
            event.preventDefault();
        });

        $("a[name='removeline']").click(function(){
 开发者_JS百科           var i = $("input[name='counter']").val();
            if(i > 1){
                $("tr[id='row"+i+"']").remove();
                $("input[name='counter']").val( Number($("input[name='counter']").val()) - 1 );
            }
            event.preventDefault();
        });

        $(".unit_price").keyup(function() {
            $(this).keyup(function(){
                calculateSumNoTax();
            });
        });
    });

    function calculateSumNoTax() {
        var sum = 0;
        //iterate through each textboxes and add the values
        $(".unit_price").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
        $("#notax").html(sum.toFixed(2));
    }


When a new line is added dynamically, the event listener (keyup function) is not attached to it.

It has to be done separately. Event listeners can be added to the "line" as soon as it is live (created).


I just found the answer here : Jquery .keypress on a dynamically added input

Changed to :

$(".unit_price").live('keypress', function(e){ $(this).keyup(function(){ calculateSumNoTax(); }); });

0

精彩评论

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

关注公众号