views:

34

answers:

2

Hi, I have a form on an order page which I need to update line totals on when the user changes the quantity. I have the grand total working, but cannot get line totals because I cannot figure out how to target the correct element.

The form is generated by a cms so ends up wrapped in lots of extraneous divs etc, ...this is a simplified version of each line item:

       <input type="text" class="text cart_qty" id="Form_OrderForm_Product-1065-qty" name="Product[1065][qty]" value="1" />

        <input type="text" class="text prod_id" id="Form_OrderForm_prod_1065" name="prod_1065" value="1065" />

        <input class="hidden" type="hidden" id="Form_OrderForm_hidden_1065" name="hidden_1065" value="1.45" />

        <span id='Product_1065_Line' class='cart_price_line'>1.45</span>

so basically, whenever the .cart_qty input field is changed, .cart_price_line needs to be updated.

I have the totals working like this:

$('.cart_qty').keyup(function(){
var $thetotal=0;

$('input.cart_qty').each(function(index) {

 $theqty=$(this).val();
 $thenextindex=$("input").index(this) + 2;
 $theprice=$("input:eq("+$thenextindex+")").val();

 $thelinetotal=$theqty * $theprice;
 $thetotal=$thetotal + $thelinetotal;

});
$("#total_price_curr").html($thetotal).formatCurrency();
$("#Form_OrderForm_totalHidden").val($thetotal);


});

It's calculating line items ok, but I can't figure out how to target the span.cart_price_line inside the $("input.cart_qty").each(...) function.

Any help would be appreciated

A: 

Would't that be this.children("span.cart_price_line")

Yves M.
span.cart_price_lin isn't a child tho, it's a sibling
galilee
A: 

I'm not sure I got what you asked for, but maybe this will help. Add this to the end of the .each() function

var product_id = $(this).attr("id").split("-")[1];
$("#Product_" + product_id + "_Line").html($thelinetotal);

Demo with that line added: http://jsfiddle.net/7NCdQ/

Also, I rewrote it (new jQuery selector to get price and renamed variables)

$('input.cart_qty').keyup(function(){
    var total = 0;

    $('input.cart_qty').each(function(index) {
        var product_id = $(this).attr("id").split("-")[1];

        var quantity = $(this).val();
        var price = $("#Form_OrderForm_hidden_" + product_id).val();

        var line_total =  price * quantity;
        total += line_total;

        $("#Product_" + product_id + "_Line").html(line_total);
    });

    $("#total_price_curr").html(total);
    $("#Form_OrderForm_totalHidden").val(total);
});

Demo: http://jsfiddle.net/7NCdQ/1/

Simen Echholt