PDA

View Full Version : Please Help With Last Child Loop



GreggH
04-04-2009, 03:11 AM
Hi its a bit of a complicated one to explain and I'm sorry I don't have a online example to show you but hopefully someone can help me.

I'm trying to build a drag and drop shopping cart, all is going well except i'm having trouble displaying the price of the last item dropped in to the cart.

What I have done is given each item a custom attribute of price = "3.99" for example, then when i drop the item in the shopping cart div i get the last childs attributes and display that:

the two ways i have been trying is this;


function cartPrice(){
var total = document.getElementById('cart').lastChild.attributes['price'].nodeValue;
document.getElementById('cartTotal').innerHTML = ('Your Total Is $' + [total]);
}

This works ok if i use it with a button and click to update price but wont update automatically in the drop function, firbug tells me cartTotal is undefined.

the other one is this:


function cartTotal(){
var itemsInShoppingCart = document.getElementById('cart').getElementsByTagName('*');
for(i=0;i<=itemsInShoppingCart.length-1;i++)
var total = itemsInShoppingCart[i].attributes['price'].nodeValue;
document.getElementById('cartTotal').innerHTML = ('Your Total Is $' + [total]);

}
which works except it displays the price of the 2nd to last child and if i remove the -1 from the length it doesnt work at all.

Do you have any Ideas how i could fix this?

Edit: I managed to get a test page online here (http://gosolutionx.com/fallen_angel/test.php) So you might better understand the problem.

dan.technician
04-05-2009, 07:55 PM
I'm not an expert in this but have you tried to change -1 into -2, 0 or even 1 and see what happens?
Hope this helps.
Dan

dan.technician
04-05-2009, 08:05 PM
have a look at the code to this site - it has a drag and drop shopping cart that counts properly etc. which I find interesting too as well as helpful.
Hope this helps.
Dan.