In JavaScript how do I reach the value of objects inside of an array - javascript

Hi im writing a funciton in JavaScript
Question: Define a function viewCart which does not accept any arguments. This function should loop over every item in cart to print out "In your cart you have [item and price pairs].". If there isn't anything in your cart, the function should print out "Your shopping cart is empty.".
here is what I have
var cart = [];
function setCart(newCart) {
cart = newCart;
}
function getCart() {
return cart;
}
function addToCart(item) {
var price = Math.floor(Math.random() * 10);
cart.push({
item: price
});
console.log(item + " has been added to your cart.");
return cart;
}
function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {
var ItemPriceObj = cart[i];
var item = Object.keys(ItemPriceObj);
var price = ItemPriceObj['item'];
newArray.push(` ${item} at \$${price}`)
}
console.log(`In your cart, you have ${newArray}.`);
} else {
return console.log('Your shopping cart is empty.');
}
}
My output:
'In your cart, you have socks at $undefined, puppy at $undefined, iPhone at $undefined.'
Wanted Output:
'In your cart, you have socks at $3, puppy at $23, iPhone at $400.'

From Tibrogargan's comment:
function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {
var ItemPriceObj = cart[i];
var item = Object.keys(ItemPriceObj);
var price = ItemPriceObj['item'];
newArray.push("" + item + " at $" + price)
}
console.log("In your cart, you have " + newArray.join(","));
} else {
return console.log('Your shopping cart is empty.');
}
}
Using "interpolated strings" isn't valid in Javascript, instead you must concatenate them

Here is something you could do. Updated the item Name and price retrieval.
var cart = [];
function setCart(newCart) {
cart = newCart;
}
function getCart() {
return cart;
}
function addToCart(item) {
var price = Math.floor(Math.random() * 10);
var obj = {};
obj[item] = price;
cart.push(obj);
console.log(item + " has been added to your cart.");
return cart;
}
function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {
var itemPriceObj = cart[i];
var itemKeys = Object.keys(itemPriceObj);
var item = itemKeys.filter(function(key) {
return itemPriceObj.hasOwnProperty(key)
});
var price = itemPriceObj[item];
newArray.push(`${item} at $${price}`);
}
console.log(`In your cart, you have ${newArray}.`);
} else {
return console.log('Your shopping cart is empty.');
}
}
addToCart("Sock");
addToCart("Phone");
addToCart("Tab");
addToCart("Book");
addToCart("Keyboard");
viewCart();

You're indexing your cart item using the string "item", not the actual item name. Very easy fix:
Change this line:
var price = ItemPriceObj['item'];
To this:
var price = ItemPriceObj[item];
Maybe want to consider changing your cart element property names (mainly for readability), but also to make some things a little easier to do, for instance:
function addToCart(newItem) {
var price = Math.floor(Math.random() * 10);
cart.push({
item: newItem, price: price
});
console.log(newItem+ " has been added to your cart.");
return cart;
}
function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {
newArray.push(` ${cart[i].item} at \$${cart[i].price}`)
}
console.log(`In your cart, you have ${newArray}.`);
} else {
return console.log('Your shopping cart is empty.');
}
}
Alternative for viewCart (some may argue at a cost to readability) - but this would be even more verbose if the property names were variable
function viewCart() {
if (cart.length != 0) {
console.log(cart.reduce( (p,e,i) => `${p}${i?',':''} ${e.item} at \$${e.price}`, "In your cart, you have" ));
} else {
return console.log('Your shopping cart is empty.');
}
}
Using language features to make the code more "simple":
var cart = [];
function Item(item, price) {
this.item = item;
this.price = price;
}
Item.prototype.toString = function() {
return `${this.item} at \$${this.price}`
}
function addToCart(item, price) {
if (!(item instanceof Item)) {
if (typeof price === "undefined") {
price = Math.floor(Math.random() * 10);
}
item = new Item(item, price);
}
cart.push( item );
console.log(item + " has been added to your cart.");
return cart;
}
function viewCart() {
if (cart.length != 0) {
console.log(`In your cart, you have ${cart.join(", ")}`);
} else {
return console.log('Your shopping cart is empty.');
}
}
addToCart("socks", 3.00);
addToCart("puppy", 23.00);
addToCart("iPhone", 400.0);
document.addEventListener( "DOMContentLoaded", viewCart, false );

You aren't using the object literal notation correctly. You probably want something like this.
Change addToCart() to this:
function addToCart(item) {
var price = Math.floor(Math.random() * 10);
cart.push({
item: item,
price: price
});
console.log(item + " has been added to your cart.");
return cart;
}
And change viewCart() to this:
function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {
newArray.push(` ${cart[i].item} at \$${cart[i].price}`)
}
var itemPriceList = newArray.join(', '); // This will concatenate all the strings in newArray and add commas in between them
console.log(`In your cart, you have ${itemPriceList}.`);
} else {
return console.log('Your shopping cart is empty.');
}
}

Related

My items don't save in local storage when I refresh the page?

The piece of code I have here is for a shopping cart. I have a function to save the cart when A new Item is added, but when I refresh the page it doesn't save, is it the save function itself?. If anyone has any idea as to why that would be great, thank you so much in advance. Here is the program, from the top it is my jQuery function that adds an extra item to the cart each time the product is clicked, from there down its mostly functions and calling functions.
$(".add-to-cart").click(function(event){
event.preventDefault();//prevents links from doing default behavior
var name = $(this).attr("data-name"); //gets the data name from the link clicked.
var price = Number($(this).attr("data-price"));
addItemToCart(name, price, 1);
displayCart();
saveCart();
});
function displayCart() {
var cartArray = listCart();
var output = "";
for (var i in cartArray){
output += "<li>"+ cartArray[i].name+ " "+ cartArray[i].count + "</li>"
}
$("#Show-cart").html(output); // this replaces the inner html of the element " Show Cart"
$("#total-cart").html(totalCart());
}
// ********************************************
// Shopping Cart Functions
//array
var cart = [];
//object
var Item = function (name, price, count)
{
this.name = name
this.price = price
this.count = count
};
function addItemToCart (name, price, count){
for (var i in cart){
if (cart[i].name === name){
cart[i].count +=count;
saveCart();
return;
}
}
var item = new Item(name, price, count);
cart.push(item);
saveCart();
}
function removeItemFromCart(name) {
for (var i in cart){
if (cart[i].name === name){
cart [i].count --;
if (cart[i].count <=0)
{
cart.splice(i, 1);
//cart[i].count =0;
}
break;
}
}
saveCart();
}
function removeItemAltogether (name)
{
for (var i in cart ) {
if (cart[i].name === name){
cart.splice(i, 1);
break;
}
}
saveCart();
}
function emptyCart (){
cart = [];
saveCart()
}
emptyCart();
console.log(cart);
function countCart(){
var total = 0;
for (var i in cart ){
total += cart[i].count;
}
return total;
}
function totalCart () {
var totalCost = 0;
for (var i in cart ){
totalCost += cart[i].price * cart[i].count;
}
return totalCost;
}
console.log(totalCart());
function listCart() {
var cartCopy = [];
for (var i in cart){
var item = cart[i];
var itemCopy = {};
for (var p in item) {
itemCopy[p] = item[p];
}
cartCopy.push (itemCopy);
}
return cartCopy;
}
function saveCart(){
localStorage.setItem("shoppingCart", JSON.stringify(cart));
}
function loadCart(){
cart =JSON.parse(localStorage.getItem("shoppingCart"));
}
addItemToCart("Apple", 1.99, 1);
loadCart();
displayCart();
The problem is that you're calling addItemToCart("Apple", 1.99, 1); when the page is loaded, before you call loadCart();. This is adding the Apple to the empty cart, then saving it, which overwrites the saved cart.
Change the order of those two lines, or remove the addItemToCart() call.
Also, loadCart() needs to handle the initial case where there's no cart saved.
function loadCart(){
var cartJSON = localStorage.getItem("shoppingCart");
cart = cartJSON ? JSON.parse(cartJSON) : [];
}
Another problem: you call emptyCart() immediately after defining it, that's clearing out the cart.

Function returning undefined after calling in string

I'm trying to make a shopping cart using JS and one of my tasks is to create a placeOrder function.
The placeOrder() function accepts one argument, a credit card number.
If no argument is received, the function should print out Sorry, we don't have a credit card on file for you.
If a card number is received, the function should print out Your total cost is $71, which will be charged to the card 83296759. Then, it should empty the cart array.
However, when I call in the total function into the string keeps returning undefined.
var cart = [];
function getCart() {
return cart;
}
function setCart(c) {
cart = c;
return cart;
}
function addToCart(itemName) {
var object = {
[itemName]: Math.floor(Math.random(1, 100) * 100)
};
cart.push(object);
console.log(`${itemName} has been added to your cart`);
return cart;
}
function total() {
if (cart.length !== 0) {
var totalValue = [];
for (var i = 0; i < cart.length; i++) {
for (var item in cart[i]) {
totalValue.push(cart[i][item]);
var sum = totalValue.reduce(function(a, b) {
return a + b;
}, 0);
console.log(`The total value is ${sum}`);
}
}
} else {
return ("Your shopping cart is empty.")
}
}
function placeOrder(cardNumber) {
if (cardNumber === undefined) {
return ("Sorry, we don't have a credit card on file for you.");
} else {
console.log(`Your total cost is $${total()}, which will be charged to the card ${cardNumber}`);
cart = [];
return cart;
}
}
addToCart("a");
addToCart("be");
addToCart("cart");
placeOrder(14564);
Output:
Your total cost is $undefined, which will be charged to the card 14564
There is no return of the function total when cart.length != 0.
You have to return sum.
if (cart.length !== 0) {
var sum = 0;
for(var i=0; i< cart.length; i++) {
for(var item in cart[i]) {
totalValue.push(cart[i][item]);
sum = totalValue.reduce(function(a, b) {return a + b;}, 0);
console.log(`The total value is ${sum}`);
}
}
return sum;
}
As #Carcigenicate said, you should call return something at the end of your if(cart.length !== 0) {} statment. Remember that when return is called, the function stops it's exectution immediatly, with no evaluation of the further instructions.
I don't know what's the purpose of that array totalValue but you don't need that function reduce, just loop over items and sum the amounts.
You're looping through the values of each item, get the amount of your items directly using Object.values(cart[i]).pop();.
var sum = 0;
for (var i = 0; i < cart.length; i++) {
var amount = Object.values(cart[i]).pop();
sum += amount;
}
Finally, return that sum.
var cart = [];
function getCart() {
return cart;
}
function setCart(c) {
cart = c;
return cart;
}
function addToCart(itemName) {
var object = {
[itemName]: Math.floor(Math.random(1, 100) * 100)
};
cart.push(object);
console.log(`${itemName} has been added to your cart`);
return cart;
}
function total() {
if (cart.length !== 0) {
var sum = 0;
for (var i = 0; i < cart.length; i++) {
for (var item in cart[i]) {
sum += cart[i][item];
}
}
console.log(`The total value is ${sum}`);
return sum;
}
return -1; // Could be 0, this is up to you.
}
function placeOrder(cardNumber) {
if (cardNumber === undefined) {
return ("Sorry, we don't have a credit card on file for you.");
} else {
var sum = total();
if (sum) {
console.log(`Your total cost is $${sum}, which will be charged to the card ${cardNumber}`);
} else {
console.log("Your shopping cart is empty.")
}
cart = [];
return cart;
}
}
addToCart("a");
addToCart("be");
addToCart("cart");
placeOrder(14564);
You'll want to make sure total always returns a number, e.g.:
var cart = [{
"a": 86
},
{
"be": 2
},
{
"cart": 24
}
];
function total(cart) {
return cart
.reduce(function(prices, item) {
return prices.concat(Object.keys(item).map(k => item[k]));
}, [])
.reduce(function(sum, price) {
return sum += price;
}, 0);
}
console.log(total([]));
console.log(total(cart));
The usage in placeOrder might look like this then:
function total(cart) {
return cart
.reduce(function(prices, item) {
return prices.concat(Object.keys(item).map(k => item[k]));
}, [])
.reduce(function(sum, price) {
return sum += price;
}, 0);
}
function placeOrder(cardNumber, cart) {
if (cardNumber === undefined) {
return "Sorry, we don't have a credit card on file for you.";
}
if (cart.length === 0) {
return "You cart is empty";
}
return `Your total cost is $${total(cart)}, which will be charged to the card ${cardNumber}`;
return [];
}
console.log(placeOrder(1234, []));
console.log(placeOrder(1234, [{
a: 1
}, {
b: 2
}]));

Hide shopping cart if is empty

For a few days in a row I've tried to find a solution to hide an entire section if my shopping cart is empty and only be shown when I add a new item in cart. Shop is made entirely with javascript and jQuery.
Down below I will put the code , even a small idea is good.
P.S: I need to hide the div.
$(".add-to-cart").click(function(event){
event.preventDefault();
var name = $(this).attr("data-name");
var price = Number($(this).attr("data-price"));
shoppingCart.addItemToCart(name, price, 1);
displayCart();
});
$("#clear-cart").click(function(event){
shoppingCart.clearCart();
displayCart();
});
function displayCart() {
var cartArray = shoppingCart.listCart();
console.log(cartArray);
var output = "";
for (var i in cartArray) {
output += "<li>"
+cartArray[i].name
+" <input class='item-count' type='number' data-name='"
+cartArray[i].name
+"' value='"+cartArray[i].count+"' >"
+" x "+cartArray[i].price
+" = "+cartArray[i].total
+" <button class='plus-item' data-name='"
+cartArray[i].name+"'>+</button>"
+" <button class='subtract-item' data-name='"
+cartArray[i].name+"'>-</button>"
+" <button class='delete-item' data-name='"
+cartArray[i].name+"'>X</button>"
+"</li>";
}
$("#show-cart").html(output);
$("#count-cart").html( shoppingCart.countCart() );
$("#total-cart").html( shoppingCart.totalCart() );
}
$("#show-cart").on("click", ".delete-item", function(event){
var name = $(this).attr("data-name");
shoppingCart.removeItemFromCartAll(name);
displayCart();
});
$("#show-cart").on("click", ".subtract-item", function(event){
var name = $(this).attr("data-name");
shoppingCart.removeItemFromCart(name);
displayCart();
});
$("#show-cart").on("click", ".plus-item", function(event){
var name = $(this).attr("data-name");
shoppingCart.addItemToCart(name, 0, 1);
displayCart();
});
$("#show-cart").on("change", ".item-count", function(event){
var name = $(this).attr("data-name");
var count = Number($(this).val());
shoppingCart.setCountForItem(name, count);
displayCart();
});
displayCart();
// Shopping Cart functions
var shoppingCart = (function () {
// Private methods and properties
var cart = [];
function Item(name, price, count) {
this.name = name
this.price = price
this.count = count
}
function saveCart() {
localStorage.setItem("shoppingCart", JSON.stringify(cart));
}
function loadCart() {
cart = JSON.parse(localStorage.getItem("shoppingCart"));
if (cart === null) {
cart = []
}
}
loadCart();
// Public methods and properties
var obj = {};
obj.addItemToCart = function (name, price, count) {
for (var i in cart) {
if (cart[i].name === name) {
cart[i].count += count;
saveCart();
return;
}
}
console.log("addItemToCart:", name, price, count);
var item = new Item(name, price, count);
cart.push(item);
saveCart();
};
obj.setCountForItem = function (name, count) {
for (var i in cart) {
if (cart[i].name === name) {
cart[i].count = count;
break;
}
}
saveCart();
};
obj.removeItemFromCart = function (name) { // Removes one item
for (var i in cart) {
if (cart[i].name === name) { // "3" === 3 false
cart[i].count--; // cart[i].count --
if (cart[i].count === 0) {
cart.splice(i, 1);
}
break;
}
}
saveCart();
};
obj.removeItemFromCartAll = function (name) { // removes all item name
for (var i in cart) {
if (cart[i].name === name) {
cart.splice(i, 1);
break;
}
}
saveCart();
};
obj.clearCart = function () {
cart = [];
saveCart();
}
obj.countCart = function () { // -> return total count
var totalCount = 0;
for (var i in cart) {
totalCount += cart[i].count;
}
return totalCount;
};
obj.totalCart = function () { // -> return total cost
var totalCost = 0;
for (var i in cart) {
totalCost += cart[i].price * cart[i].count;
}
return totalCost.toFixed(2);
};
obj.listCart = function () { // -> array of Items
var cartCopy = [];
console.log("Listing cart");
console.log(cart);
for (var i in cart) {
console.log(i);
var item = cart[i];
var itemCopy = {};
for (var p in item) {
itemCopy[p] = item[p];
}
itemCopy.total = (item.price * item.count).toFixed(2);
cartCopy.push(itemCopy);
}
return cartCopy;
};
// ----------------------------
return obj;
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul>
<li><a class="add-to-cart" href="#" data-name="Apple" data-price="1.22">Apple $1.22</a></li>
<li><a class="add-to-cart" href="#" data-name="Banana" data-price="1.33">Banana $1.33</a></li>
<li><a class="add-to-cart" href="#" data-name="Shoe" data-price="22.33">Shoe $22.33</a></li>
<li><a class="add-to-cart" href="#" data-name="Frisbee" data-price="5.22">Frisbee $5.22</a></li>
</ul>
<button id="clear-cart">Clear Cart</button>
</div>
<div>
<ul id="show-cart">
<li>???????</li>
</ul>
<div>You have <span id="count-cart">X</span> items in your cart</div>
<div>Total Cart:$<span id="total-cart"></span></div>
</div>
To hide the div, you will need to modify the displayCart() as below.
function displayCart() {
var cartArray = shoppingCart.listCart();
console.log(cartArray);
var output = "";
var divEl = $("#show-cart").parent();
if(cartArray.length > 0) {
for (var i in cartArray) {
output += "<li>"
+cartArray[i].name
+" <input class='item-count' type='number' data-name='"
+cartArray[i].name
+"' value='"+cartArray[i].count+"' >"
+" x "+cartArray[i].price
+" = "+cartArray[i].total
+" <button class='plus-item' data-name='"
+cartArray[i].name+"'>+</button>"
+" <button class='subtract-item' data-name='"
+cartArray[i].name+"'>-</button>"
+" <button class='delete-item' data-name='"
+cartArray[i].name+"'>X</button>"
+"</li>";
}
$(divEl).removeClass('hidden');
} else {
$(divEl).addClass('hidden');
}
$("#show-cart").html(output);
$("#count-cart").html( shoppingCart.countCart() );
$("#total-cart").html( shoppingCart.totalCart() );
}
So that way it will show or hide the div depending on the size of the object.
Try and comment.
PS: hidden is a bootstrap class. You will need to include the bootstrap library. Or instead just add the css picked up from the library if you don't need it entirely.
.hidden {
display: none !important;
}
You could use the length of cart items as boolean for jQuery toggle()
let $cartList = $('#show-cart');
$cartList.parent().toggle( $cartList.children().length );

azure asynchronous javascript backend - wait function

I'm using Azure Mobile Services and a javascript backend. My problem is that the function don't wait the end of an other function.
I'm trying to choose an item (word) with a particolar rules. i want to pick the item with highest item.wordnumber. If there are few item with the same item.wordnumber i want to pick who has a highest avarage of votes associated at that item (in the other table "votes").
This script don't wait the return of function CalcolateMaxAvg.
I would do as I did in c # with await.
var tableWords = tables.getTable('Word');
var tableVotes = tables.getTable('Votes');
var avgVotesActualWord = 0;
var maxItem = null;
var maxItemVote = 0;
function WordChoice() {
var select = tableWords.orderByDescending('wordnumber').read({success:
function (results)
{
results.forEach(function(item)
{
if(maxItem == null)
{
maxItem = item;
maxItemVote = tableVotes.where({idword: item.id}).read({success: CalcolateMaxAvg});
}
else if(item.wordnumber > maxItem.wordnumber)
{
maxItem = item;
maxItemVote = tableVotes.where({idword: item.id}).read({success: CalcolateMaxAvg});
}
else if(item.wordnumber == maxItem.wordnumber)
{
//chack who have more votes
avgVotesActualWord = 0;
avgVotesActualWord = tableVotes.where({idword: item.id}).read({success: CalcolateMaxAvg});
//the problem is avgVoteActualWord that is always NaN
console.log('Word: %s with avg: %d', item.word, avgVotesActualWord);
if(avgVotesActualWord > maxItemVote)
{
//take the actualword because have more votes
maxItem = item;
maxItemVote = avgVotesActualWord;
}
}
})
if(maxItem != null)
{
console.log('parola: %s', maxItem.word);
maxItem.selected = true;
tableWords.update(maxItem);
}
else
{
console.log('null');
}
}
});
}
function CalcolateMaxAvg(resultsVote)
{
var sum = 0;
var count = 0;
var avg = 0;
resultsVote.forEach(function(itemVote)
{
sum = sum + itemVote.vote;
count = count + 1;
})
if(count > 0)
{
avg = sum / count;
}
//this is a correct value of avgVoteActualWord, but he don't wait the return of this value
console.log('avg: %d', avg);
return avg;
}
The problem is that a call to table.where(...).read(...) is asynchronous - it won't return a number returned by the CalcolateMaxAvg function (it won't return anything). You need to rewrite your code to embrace the asynchronicity of JavaScript, something along the lines of the code below.
var tableWords = tables.getTable('Word');
var tableVotes = tables.getTable('Votes');
var avgVotesActualWord = 0;
var maxItem = null;
var maxItemVote = 0;
function WordChoice() {
var select = tableWords.orderByDescending('wordnumber').read({
success: function (results)
{
function processNextResult(index) {
if (index >= results.length) {
// All done
if(maxItem != null)
{
console.log('parola: %s', maxItem.word);
maxItem.selected = true;
tableWords.update(maxItem);
}
else
{
console.log('null');
}
return;
}
var item = results[index];
if (maxItem == null) {
maxItem = item;
tableVotes.where({ idword: item.id }).read({ success: simpleProcessVotesResult });
} else if (item.wordnumber > maxItem.wordnumber) {
maxItem = item;
tableVotes.where({ idword: item.id }).read({ success: simpleProcessVotesResult });
} else if (item.wordnumber == maxItem.wordnumber) {
//check who have more votes
avgVotesActualWord = 0;
tableVotes.where({idword: item.id}).read({
success: function(resultsVote) {
avgVotesActualWord = CalcolateMaxAvg(resultsVote);
//the problem is avgVoteActualWord that is always NaN
console.log('Word: %s with avg: %d', item.word, avgVotesActualWord);
if(avgVotesActualWord > maxItemVote)
{
//take the actualword because have more votes
maxItem = item;
maxItemVote = avgVotesActualWord;
}
processNextResult(index + 1);
}
});
} else {
processNextResult(intex + 1);
}
}
function simpleProcessVotesResult(resultsVote) {
maxItemsVote = CalcolateMaxAvg(resultsVote);
processNextResult(intex + 1);
}
processNextResult(0);
}
});
}
function CalcolateMaxAvg(resultsVote)
{
var sum = 0;
var count = 0;
var avg = 0;
resultsVote.forEach(function(itemVote)
{
sum = sum + itemVote.vote;
count = count + 1;
})
if(count > 0)
{
avg = sum / count;
}
//this is a correct value of avgVoteActualWord, but he don't wait the return of this value
console.log('avg: %d', avg);
return avg;
}

How to display a field in shopping cart regarding the bag in which item was dropped using jquery

I am very new to jQuery. I am presently working on a project. In this project there are 3 types of items and three bags such that the user should select anyone of the bags and try dropping items into it. If the user selects bag 1 then he can drop item1, item2, item3 if he selects bag 2 he can drop item2, item3 if he selects bag3 he can drop item3 only.
Now the problem is I have added an additional field bag to display the type of bag in which the item was dropped (example "bag1" or "bag2" or "bag3").
But the problem is I am unable to display the bag field. Do anyone out there let me know what I can do. I am struggling a lot for this.
Example on jsfiddle: http://jsfiddle.net/Vwu37/48/
HTML:
<tr>
<th field="name" width=140>Name</th>
<th field="bag" width=60>Bag</th>
<th field="quantity" width=60 align="right">Quantity</th>
<th field="price" width=60 align="right">Price</th>
<th field="remove" width=60 align="right">Remove</th>
</tr>
Javascript:
var data = {
"total": 0,
"rows": []
};
var totalCost = 0;
$(function () {
$('#cartcontent1').datagrid({
singleSelect: true
});
$('.bag').droppable({
onDrop: function (e, source) {
var name = $(source).find('p:eq(0)').html();
var price = $(source).find('p:eq(1)').html();
addProduct(name, parseFloat(price.split('$')[1]));
$(source.draggable).remove();
//$('.bag').droppable('enable');
$(this).droppable('enable');
}
});
$('.item').each(function (index, div) {
var scope = $(this).attr('data-scope');
//debugger;
$(div).draggable({
revert: true,
proxy: 'clone',
onStartDrag: function () {
$('.bag').droppable('enable');
$('.bag:not(.selected)').droppable('disable');
$('.bag:not(.bag[data-scope*=' + scope + '])').droppable('disable');
$(this).draggable('options').cursor = 'not-allowed';
$(this).draggable('proxy').css('z-index', 10);
},
onStopDrag: function () {
//$('.bag').droppable('enable');
$(this).draggable('options').cursor = 'move';
}
});
});
$('.bag').click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected');
});
});
function addProduct(name, price) {
var totalQuantity = sumQuantity(data);
if (totalQuantity < 10) {
function add() {
for (var i = 0; i < data.total; i++) {
var row = data.rows[i];
if (row.name == name) {
row.quantity += 1;
return;
}
}
data.total += 1;
data.rows.push({
name: name,
quantity: 1,
price: price,
remove: 'X'
});
}
add();
totalCost += price;
$('#cartcontent1').datagrid('loadData', data);
$('div.cart .total').html('Total: $' + totalCost);
} else {
alert('cannot have more than 10 items');
}
}
function removeProduct(el, event) {
var tr = $(el).closest('tr');
var name = tr.find('td[field=name]').text();
var price = tr.find('td[field=price]').text();
var quantity = tr.find('td[field=quantity]').text();
for (var i = 0; i < data.total; i++) {
var row = data.rows[i];
if (row.name == name) {
data.rows.splice(i, 1);
data.total--;
break;
}
}
totalCost -= price * quantity;
$('#cartcontent1').datagrid('loadData', data);
$('div.cart .total').html('Total: $' + totalCost);
}
function sumQuantity(data) {
var sum = 0;
for (var i = 0; i < data.total; i++) {
sum += data.rows[i].quantity;
}
return sum;
}
I updated the bag html to include a bag id. In the onDrop function i added e.target.id to get the id of the bag.
$('.bag').droppable({
onDrop: function (e, source) {
var name = $(source).find('p:eq(0)').html();
var price = $(source).find('p:eq(1)').html();
var bag = e.target.id;
addProduct(name, parseFloat(price.split('$')[1]), bag);
$(source.draggable).remove();
//$('.bag').droppable('enable');
$(this).droppable('enable');
}
});
Pass this bag id to the addProduct function. Se the example in http://jsfiddle.net/Vwu37/55/ Is this what you had in mind?
Edit: It looks like there is a problem when you add the same item to two different bags. I am not sure if you want to be able to add the same item to different bags. If you want to do this you can change your addProduct function with if (row.name == name && row.bag == bag)
function addProduct(name, price, bag) {
var totalQuantity = sumQuantity(data);
if (totalQuantity < 10) {
function add() {
for (var i = 0; i < data.total; i++) {
var row = data.rows[i];
if (row.name == name && row.bag == bag) {
row.quantity += 1;
return;
}
}
data.total += 1;
data.rows.push({
name: name,
bag: bag,
quantity: 1,
price: price,
remove: 'X'
});
}
add();
totalCost += price;
$('#cartcontent1').datagrid('loadData', data);
$('div.cart .total').html('Total: $' + totalCost);
} else {
alert('cannot have more than 10 items');
}
}

Categories

Resources