Итак, я пытаюсь сделать сводную страницу со страницы корзины. Когда я нажимаю CHECK OUT, мы записываем текст в другой документ html и очищаем корзину.
Проблема в том, что при нажатии на компонент, который является тегом (добавлено событие щелчка), он не будет записываться в выбранное тело. Однако он только опустошит корзину.
Если я вызову метод, который записывает данные в таблицу, а не нажимает кнопку, то все появляется.
Любая помощь будет принята с благодарностью, так как я новый для JavaScript & JQuery.
JS ФАЙЛ
$(document).ready(function() {
fetch("shoes.json")
.then(resp => resp.json())
.then(data => {
let shoes = data.shoes;
loadAllFunctions(shoes);
})
.catch(err => console.error(err));
function loadAllFunctions(shoes) {
let products = JSON.parse(localStorage.products || "[]");
updateItemCount();
loadCart();
showOrHideButtons();
// LADDAR UPP CART SIDAN MED ALLA PRODUKTER MED EN TABELL
function loadCart() {
let total = 0;
let cartArea = $(".cart-area");
let tableText = "<table id='soc' class='table mt-5'><thead class='thead-dark'><tr>" +
"<th scope='col'>Article</th><th scope='col'></th><th scope='col'>Quantity</th><th scope='col'>Price</th><th scope='col'>Remove</th>" +
"</tr></thead><tbody>";
if(products.length != 0) {
products.forEach(shoe => {
let shoeTotal = (shoe.price * shoe.quantity);
tableText += "<tr><td>" + "<img src=" + shoe.image + "></td>" +
"<td class='font-weight-bold'><div class='mt-5'>" + shoe.name + "</div></td><td><div class='mt-5'>" + "<input class='cart-input' id=" + shoe.id + " type='number' min=0 value='" + shoe.quantity + "'></div>" + "</td>" +
"<td class='font-weight-bold'><div id='" + shoe.id + "' class='price mt-5'>kr " + shoeTotal + "</div></td><td><button id='" + shoe.id + "' class='delete ml-3 mt-5'>X</button></td></tr>";
total += shoeTotal;
});
tableText += "</tbody></table><hr><h4 id='total-amount' class='text-dark mb-5'><b>Total Amount:</b> kr " + total + "</h4>";
cartArea.html(tableText);
}
else {
cartArea.html("<h3 class='m-5'>There are no items in your cart.</h3><a id='continue-btn' class='ml-5' href='shopping.html'>CONTINUE SHOPPING</a>");
}
let deleteButton = $(".delete");
deleteButton.click(function() {
let clickedDeleteID = $(this).attr("id");
products = removeShoe(clickedDeleteID);
localStorage.setItem("products", JSON.stringify(products));
showOrHideButtons();
loadCart();
updateItemCount();
});
let cartInput = $(".cart-input");
cartInput.change(updateShoeQuantity);
//
function updateShoeQuantity() {
let totalAmount = $("#total-amount");
let totalText = 0;
let qtyInput = $(this);
let tempID = qtyInput.attr("id");
let qtyValue = parseInt(qtyInput.val());
let shoetotalPrice = $("#" + tempID + ".price"); // hämtar innehållet i denna
if(qtyValue < 0) {
qtyValue = 0;
}
for (let i = 0; i < products.length; i++) {
const shoe = products[i];
if(shoe.id == tempID) {
if(qtyValue != 0) {
shoe.quantity = qtyValue;
shoetotalPrice.html("kr " + (shoe.price * shoe.quantity))
break;
}
else {
products = removeShoe(shoe.id);
loadCart();
break;
}
}
}
localStorage.setItem("products", JSON.stringify(products));
updateItemCount();
showOrHideButtons();
for (let j = 0; j < products.length; j++) {
const shoe = products[j];
totalText += (shoe.price * shoe.quantity);
}
totalAmount.html("<b>Total Amount:</b> kr " + totalText);
}
}
function removeShoe(ID) {
let tempProducts = [];
products.forEach(shoe => {
if(shoe.id != ID) {
tempProducts.push(shoe);
}
});
return tempProducts;
}
// UPPDATERAR ANTAL SKOR I KART KNAPPEN I NAVBAR
function updateItemCount() {
let cart = $(".cart-btn");
cart.html("");
let totalItems = 0;
products.forEach(shoe => {
totalItems += shoe.quantity;
});
if(totalItems == 1) {
cart.html(totalItems + " ITEM <img src='images/shoppingBag2.png' alt='cart'>");
}
else {
cart.html(totalItems + " ITEMS <img src='images/shoppingBag2.png' alt='cart'>");
}
}
function addToCart(cBtn) {
let clickedButton = $(cBtn);
let buttonID = clickedButton.attr("id");
let thisInput = $("#" + clickedButton.attr("id") + ".input-form").children("input");
let newShoe = {
id: buttonID,
image: shoes[buttonID].image,
name: shoes[buttonID].name,
price: shoes[buttonID].price,
quantity: parseInt(thisInput.val())
};
if (products.length != 0) {
let isExists = products.some(shoe => shoe.name === newShoe.name);
if (!isExists) {
products.push(newShoe);
} else {
products = products.map(shoe => {
if (shoe.name == newShoe.name && !isNaN(newShoe.quantity)) {
shoe.quantity += newShoe.quantity;
return shoe;
}
return shoe;
});
}
localStorage.setItem("products", JSON.stringify(products));
} else {
products.push(newShoe);
localStorage.setItem("products", JSON.stringify(products));
}
updateItemCount();
loadCart();
}
let $table = $(".shoe-table");
let rows = [1, 2, 3];
let shoeCard = "";
let counter = 0;
rows.forEach(row => {
shoeCard += "<tr>";
for (let index = 0; index < 4; index++) {
shoeCard +=
"<td class='card text-center'>" +
"<img class='card-img-top' src=" +
shoes[counter].image +
" alt='Card image cap'>" +
"<h5 class='card-title'>" +
shoes[counter].name +
"</h5>" +
"<p class='card-text'>kr " +
shoes[counter].price +
"</p>" +
"<button id=" +
counter +
" class='orderNow btn btn-outline-dark'>ORDER NOW</button>" +
"<div id=" +
counter +
" class='input-form'><input class='qty-chooser' type='number' placeholder='Choose quantity' min=0 max=10>" +
"<button class='btn-add-to-cart' disabled='disabled'>ADD TO CART</button>" +
"</div>" +
"</td>";
counter++;
}
shoeCard += "</tr>";
});
$table.append(shoeCard);
let $inputForm = $(".input-form");
let $orderBtn = $(".orderNow");
$inputForm.hide();
let activeButton = -1;
// Denna metod tittar om man redan har en aktiv beställning
function isProductActive() {
let btnID = $(this).attr("id");
if (activeButton == -1) {
activeButton = btnID;
toggleOrder($(this));
} else if (btnID != activeButton) {
toggleOrder($("#" + activeButton + ".orderNow"));
toggleOrder($(this));
activeButton = btnID;
} else if (btnID == activeButton) {
toggleOrder($(this));
activeButton = -1;
}
}
$orderBtn.click(isProductActive);
function toggleOrder(buttonC) {
console.log("INSIDE TOGGLE");
let clickedBtn = $(buttonC);
let thisInputForm = $("#" + clickedBtn.attr("id") + ".input-form");
let inputBtn = thisInputForm.children("button");
let inputIn = thisInputForm.children("input");
// RESETTAR ELEMENT I .input-form
function resetInputForm() {
inputBtn.css("background", "");
inputBtn.css("color", "");
inputBtn.attr("disabled", "disabled");
inputIn.val(null);
}
// DENNA KNAPP ÄR EN KNAPP MED ETT ANROP TILL ADDTOCART OCH RESETAR INPUTFORM
inputBtn.click(function() {
addToCart(clickedBtn);
thisInputForm.hide("slow");
clickedBtn.text("ORDER NOW");
clickedBtn.css("background", "");
resetInputForm();
activeButton = -1;
});
// BEROENDE PÅ QUANTITY REAGERAR ADD TO CART KNAPPEN
inputIn.change(function() {
let qty = inputIn.val();
if (qty >= 1 && qty <= 10) {
inputBtn.removeAttr("disabled");
inputBtn.css("background", "rgb(15, 163, 10)");
inputBtn.css("color", "white");
} else {
resetInputForm();
}
});
// KONTROLLERAR ORDER NOW KNAPPEN
if (clickedBtn.text() == "CANCEL") {
thisInputForm.hide("slow");
clickedBtn.text("ORDER NOW");
clickedBtn.css("background", "");
resetInputForm();
} else {
thisInputForm.show("slow");
clickedBtn.text("CANCEL");
clickedBtn.css("background", "red");
resetInputForm();
}
}
function showOrHideButtons() {
let bArea = $("#button-area");
if(products.length == 0) {
bArea.hide()
}
else {
bArea.show();
}
}
let emptyButton = $(".empty-button");
emptyButton.click(emptyCart);
СООТВЕТСТВУЮЩИЙ КОД
function emptyCart() {
products = [];
localStorage.setItem("products", JSON.stringify(products));
showOrHideButtons();
loadCart();
updateItemCount();
}
$(".make-order").click(loadOrderSummary);
function loadOrderSummary() {
let shoeTbody = $(".shoe-data");
let summaryText = "";
products.forEach(shoe => {
let sum = (shoe.quantity * shoe.price);
summaryText += "<tr><td>" + shoe.name + "</td>"+
"<td>" + shoe.quantity + "</td>" +
"<td>" + sum + "</td></tr>";
});
shoeTbody.html(summaryText);
emptyCart();
}
}
});
HTML DO C
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous"
/>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css" type="text/css">
<title>Order Confirmation</title>
</head>
<body>
<div class="container-fluid">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<button class="navbar-toggler mr-auto" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="index.html">
<img class="img-fluid ml-5" src="images/WebShoelogo.png" alt="logo">
</a>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav m-auto">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about.html">About us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="shopping.html">Shopping</a>
</li>
</ul>
</div>
<a class="cart-btn ml-auto" href="cart.html">
0 ITEMS
<img src="images/shoppingBag2.png" alt="cart">
</a>
</nav>
<div class="row">
<div class="col text-center"><h1 class="mt-5">Your order has been successfully placed!</h1>
<h3 class="mb-5">You will have your order within 3 - 7 business days!</h3>
</div>
</div>
<div class="row">
<div class="col-2">
</div>
<div class="col-8 mt-5 mb-5">
<table class="Order-summary table table-dark table-hover m-auto">
<thead>
<tr>
<th class="thHeader">
Order Summary
</th>
</tr>
<tr>
<th>Article</th>
<th>Quantity</th>
<th>Sum</th>
</tr>
</thead>
<tbody class="shoe-data">
<tr><td>test</td></tr>
</tbody>
</table>
</div>
<div class="col-2">
</div>
</div>
<div class="row">
<div class="col text-center">
<a id="continue-btn" class="mt-5" href="shopping.html">CONTINUE SHOPPING</a>
</div>
</div>
<div class="row">
<div class="col">
<h1 class="hideHeader">IOjdsodfjsdiofjoisjdfoij</h1>
<h1 class="hideHeader">IOjdsodfjsdiofjoisjdfoij</h1>
</div>
</div>
<div class="footer">
<br><br>
<div class="row">
<div class="col-1"></div>
<div class="col-10">
<table class="table footer-table m-auto">
<thead>
<tr>
<th class="heading">
HELP CENTER
</th>
<th class="heading">
ABOUT US
</th>
<th class="heading">
GIFT CARDS AND OTHER
</th>
<th class="heading">
CONNECT WITH US
</th>
<th>
PAYMENT METHODS
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
FAQs <br>
Sizing Guide <br>
Contact Us <br>
30 Day Trial <br>
Exchange & Returns
</td>
<td>
TRUE story <br>
Materials Matter <br>
Business Model <br>
Wayfarers Club
</td>
<td>
Wood Gift Cards (physical) <br>
E-Gift Certficates (digital) <br>
Sitemap
</td>
<td class="connect">
<a href="#">
<img src="images/instagram.png" alt="instagram">
</a>
<a href="#">
<img src="images/facebook.png" alt="facebook">
</a> <br>
<a href="#">
<img src="images/linkedin.png" alt="linkedin">
</a>
<a href="#">
<img src="images/twitter.png" alt="twitter">
</a>
</td>
<td class="payment">
<img class="img-fluid" src="images/americanex.png" alt="AE">
<img class="img-fluid" src="images/visa.png" alt="visa"><br>
<img class="img-fluid" src="images/mastercard.png" alt="MC">
<img class="img-fluid" src="images/paypal.png" alt="PP">
</td>
</tr>
</tbody>
</table>
<hr>
<div class="row">
<div class="col-2">
<img class="img-fluid ml-5" src="images/WebShoelogo.png" alt="logo">
</div>
<div class="col-6">
</div>
<div class="col-4">
<p class="ml-5">© 2020 WebShoe</p>
<a class="privacy ml-3" href="">PRIVACY POLICY</a>
</div>
</div>
</div>
<div class="col-1"></div>
</div>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script src="product.js"></script>
</body>
</html>