Question

I need help writting a Javascript function that does the following its for a HTML/CSS Shopping Cart Page

This page contains a list of the selected products that includes an image, name, price, quantity, and cost) Because the proce

The user can do the following things: 1. View and edit the shopping cart: a. Change the number of items to purchase b. Remove

CODE

<!DOCTYPE html> <html lang=en> <head> <title>Project 5 - Shopping Cart</title> <meta charset=utf-8> <link rel=stylesheet

SUNUCSS <td><input value=$35.00 size=10 disabled></td> <td> <select size =1 name=shoeQTY id=shoeQty> <option value=

<tr> <td colspan=5 class=total> Subtotal with shipping: </td> <td> <input class=sum value=$74.00 size=10 disabled> <

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Javascript code for above mention shopping cart( i am writing this code on the basis of what i understand hope this will be useful.)

// ************************************************
// Shopping Cart API
// ************************************************

var shoppingCart = (function() {
// =============================
// Private methods and propeties
// =============================
cart = [];
  
// Constructor
function Item(name, price, count) {
this.name = name;
this.price = price;
this.count = count;
}
  
// Save cart
function saveCart() {
sessionStorage.setItem('shoppingCart', JSON.stringify(cart));
}
  
// Load cart
function loadCart() {
cart = JSON.parse(sessionStorage.getItem('shoppingCart'));
}
if (sessionStorage.getItem("shoppingCart") != null) {
loadCart();
}
  

// =============================
// Public methods and propeties
// =============================
var obj = {};
  
// Add to cart
obj.addItemToCart = function(name, price, count) {
for(var item in cart) {
if(cart[item].name === name) {
cart[item].count ++;
saveCart();
return;
}
}
var item = new Item(name, price, count);
cart.push(item);
saveCart();
}
// Set count from item
obj.setCountForItem = function(name, count) {
for(var i in cart) {
if (cart[i].name === name) {
cart[i].count = count;
break;
}
}
};
// Remove item from cart
obj.removeItemFromCart = function(name) {
for(var item in cart) {
if(cart[item].name === name) {
cart[item].count --;
if(cart[item].count === 0) {
cart.splice(item, 1);
}
break;
}
}
saveCart();
}

// Remove all items from cart
obj.removeItemFromCartAll = function(name) {
for(var item in cart) {
if(cart[item].name === name) {
cart.splice(item, 1);
break;
}
}
saveCart();
}

// Clear cart
obj.clearCart = function() {
cart = [];
saveCart();
}

// Count cart
obj.totalCount = function() {
var totalCount = 0;
for(var item in cart) {
totalCount += cart[item].count;
}
return totalCount;
}

// Total cart
obj.totalCart = function() {
var totalCart = 0;
for(var item in cart) {
totalCart += cart[item].price * cart[item].count;
}
return Number(totalCart.toFixed(2));
}

// List cart
obj.listCart = function() {
var cartCopy = [];
for(i in cart) {
item = cart[i];
itemCopy = {};
for(p in item) {
itemCopy[p] = item[p];

}
itemCopy.total = Number(item.price * item.count).toFixed(2);
cartCopy.push(itemCopy)
}
return cartCopy;
}

// cart : Array
// Item : Object/Class
// addItemToCart : Function
// removeItemFromCart : Function
// removeItemFromCartAll : Function
// clearCart : Function
// countCart : Function
// totalCart : Function
// listCart : Function
// saveCart : Function
// loadCart : Function
return obj;
})();


// *****************************************
// Triggers / Events
// *****************************************
// Add item
$('.add-to-cart').click(function(event) {
event.preventDefault();
var name = $(this).data('name');
var price = Number($(this).data('price'));
shoppingCart.addItemToCart(name, price, 1);
displayCart();
});

// Clear items
$('.clear-cart').click(function() {
shoppingCart.clearCart();
displayCart();
});


function displayCart() {
var cartArray = shoppingCart.listCart();
var output = "";
for(var i in cartArray) {
output += "<tr>"
+ "<td>" + cartArray[i].name + "</td>"
+ "<td>(" + cartArray[i].price + ")</td>"
+ "<td><div class='input-group'><button class='minus-item input-group-addon btn btn-primary' data-name=" + cartArray[i].name + ">-</button>"
+ "<input type='number' class='item-count form-control' data-name='" + cartArray[i].name + "' value='" + cartArray[i].count + "'>"
+ "<button class='plus-item btn btn-primary input-group-addon' data-name=" + cartArray[i].name + ">+</button></div></td>"
+ "<td><button class='delete-item btn btn-danger' data-name=" + cartArray[i].name + ">X</button></td>"
+ " = "
+ "<td>" + cartArray[i].total + "</td>"
+ "</tr>";
}
$('.show-cart').html(output);
$('.total-cart').html(shoppingCart.totalCart());
$('.total-count').html(shoppingCart.totalCount());
}

// Delete item button

$('.show-cart').on("click", ".delete-item", function(event) {
var name = $(this).data('name')
shoppingCart.removeItemFromCartAll(name);
displayCart();
})


// -1
$('.show-cart').on("click", ".minus-item", function(event) {
var name = $(this).data('name')
shoppingCart.removeItemFromCart(name);
displayCart();
})
// +1
$('.show-cart').on("click", ".plus-item", function(event) {
var name = $(this).data('name')
shoppingCart.addItemToCart(name);
displayCart();
})

// Item count input
$('.show-cart').on("change", ".item-count", function(event) {
var name = $(this).data('name');
var count = Number($(this).val());
shoppingCart.setCountForItem(name, count);
displayCart();
});

displayCart();

Add a comment
Know the answer?
Add Answer to:
I need help writting a Javascript function that does the following its for a HTML/CSS Shopping...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • i'm having trouble with 1 and 3 using html, javascript and jquery 1) Change the "Search"...

    i'm having trouble with 1 and 3 using html, javascript and jquery 1) Change the "Search" link on the left to a button that when clicked, hide all the fields on the form and display the text "This is a search feature..." 3) When the user fills the form and clicks "Login", the values inputted should be displayed in the empty row (under Login) of the page. The display should be in the form: Student ID: <input value> Student Name:...

  • Both codes <!DOCTYPE html> <html> <head> <title>Week 8 Lab - JavaScript DOM and Arrays</title> <meta charset="utf-8">...

    Both codes <!DOCTYPE html> <html> <head> <title>Week 8 Lab - JavaScript DOM and Arrays</title> <meta charset="utf-8"> </head> <body> <h2>Order Form</h2> <form name="orderForm" method="post" action="processForm.html"> <table> <tr> <th colspan="2">Personal Information</th> </tr> <tr> <td>First Name:</td> <td><input type="text" name="firstName" id="firstName" size="30"></td> </tr> <tr> <td>Last Name:</td> <td><input type="text" name="lastName" id="lastName" size="30"></td> </tr> <tr> <td>Address:</td> <td><input type="text" name="address" id="address" size="30"></td> </tr> <tr> <td>City:</td> <td><input type="text" name="city" id="city" size="30"></td> </tr> <tr> <td>Province:</td> <td><select name="province" id="province" size="1"> <option disabled>Select a province</option> <option value="BC">British Columbia</option> <option value="AB">Alberta</option> <option...

  • HTML Coding <html> <head> <title> Contact -- Charles Robertson </title> </head> <body bgcolor="white"> <table width="700" height="500"...

    HTML Coding <html> <head> <title> Contact -- Charles Robertson </title> </head> <body bgcolor="white"> <table width="700" height="500" border="10"> <!-----row---1----logo---> <tr><td> <img src="20150516_084745" width="700" height="200"> </td></tr> <!-----row-2-navigation-----> <tr><td> <!----start-navigation-table----> <table width="700" height="100" border="5" bgcolor="lightgreen" > <tr><td><a href="HerbFarm.html"> <center> HOME </center></a></td> <td><a href="about3.html"> <center> ABOUT </center></a></td> <td><a href="contact3.html"> <center> CONTACT </center></a></td> <td><a href="gallery3.html"> <center> GALLERY </center></a></td> </tr> </table> <!------end-navigation-table----> </td></tr> <tr><td> <h1>Contact </h1> <form action="thankyou.html">    </form> <div class="row"> <div class="col-75"> <div class="container"> <form action="/action_page.php"> <div class="row"> <div class="col-50"> <h3>Billing Address</h3> <label for="fname"><i...

  • Below is the code created for a previous assignment. I now need to create functions to...

    Below is the code created for a previous assignment. I now need to create functions to validate the name, age, and item selection in an external JavaScript file. Specifically, check for the following: The user has entered a name Age is a number between 18 and 110 An item is selected Ensure that a handler returns true if the input is acceptable and false otherwise. Add an onSubmit attribute to the form tag so that a validation failure prevents the...

  • the is my HTML and CSS code. I didn't attach the image or the CSS file...

    the is my HTML and CSS code. I didn't attach the image or the CSS file because of the space limit. two things I wanted to incorporate on this page are to make "MY TOP 3 MUSIC GENRES" blink using javascript and to make the video links autoplay using javascript both should be using javascript requirement: our professor told us not to use <div> or alert. thank you for your help <!DOCTYPE html> <!-- I used w3school for the formatting...

  • How to make all the buttons work using javascript? <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta...

    How to make all the buttons work using javascript? <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script> function openAccount() { /* - get the account and initial amount values - check that all necessary information is provided - call the setCookie function to create account */ } function Deposit() { /* - get the account and amount values - check that all necessary information is provided - alter cookie with current amount of deposit */ } function...

  • I have to make a pixel art maker using javascript. HTML and CSS were already provided....

    I have to make a pixel art maker using javascript. HTML and CSS were already provided. I only had to do the JavaScript part. Every time I run the HTML folder nothing happens when I choose the width, height, and color. This is my code: (ONLY JS IS SUPPOSED TO BE FIXED). JS: // Select color input // Select size input const colorPicker = document.getElementsById('colorPicker'); const rowNum = document.getElementsById('inputHeight'); const cellNum = document.getElementById('inputWidth'); const pixelCanvas = document.getElementById('pixelCanvas'); const form =...

  • New Perspectives on HTML5 and CSS3. Solve Chapter 13 Case Problem 3. mas_register.js "use strict"; /*...

    New Perspectives on HTML5 and CSS3. Solve Chapter 13 Case Problem 3. mas_register.js "use strict"; /* New Perspectives on HTML5, CSS3, and JavaScript 6th Edition Tutorial 13 Case Problem 3 Filename: mas_register.js Author: Date: Function List ============= formTest() Performs a validation test on the selection of the conference session package and the conference discount number calcCart() Calculates the cost of the registration and saves data in session storage    writeSessionValues() Writes data values from session storage in to the registration...

  • I need help incorporating javascript into my page. The Lessons page has a message box (not...

    I need help incorporating javascript into my page. The Lessons page has a message box (not an alert box) that becomes visible/invisible when the mouse is moved over/off the small, red hyperlink on the last line that says, "note." The note is 10pt, red, and italic. The message box contains the text, "Students who pre-pay for the entire term will have the registration fee waved." It is 150px wide, with an "azure" background and a black border. It has 5px...

  • I need HELP to get the code to do these function: If I keep clicking "Generate"...

    I need HELP to get the code to do these function: If I keep clicking "Generate" multiple times, the list keeps on getting bigger. The number of rows should always be equal to the number of columns. Also make the code to show both table at the same time? Here is the code I got some far : Code: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Testing</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> </head> <style> td...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT