So I somehow built that It transfer total from checkout page to index page which is in this case payment page,But the is one problem;it automaticly goes to index page when going on checkout page but I want that it does that only when button is clicked.I tried to do something with addEventListener but it just goes on index.html? instead of something like index.html?total=320.00
heres checkout code:
<div class="total">
<form action="index.html" class="total">
<h3 style="text-align:center; display: none;">Subtotal: <br><span id="subtotal"></span></h3>
<h3 style="text-align:center;">Total: <br><span id="total">$0</span></h3>
<a><button type="submit" class="buy-btn" style="background-color: rgb(29, 4, 216);">Continue to purchase</button></a>
<a href="index.html" onclick="alert('You will be redirected to the home page')"><button style="background-color: rgb(216, 4, 4);">Cancel</button></a>
</div>
</form>
<!--It does clear but wonder , make that you cant click on button if that function is done-->
</body>
<script>
const cartItemsDiv = document.querySelector(".cart-items");
const storedCartItem = localStorage.getItem("selectedItems");
let subtotal = 0;
const continueButton = document.getElementById("buy-btn");
const clearButton = document.getElementById("clear-button");
function clearCartItems() {
// Clear the HTML content of the cart-items div
const cartItemsDiv = document.querySelector(".cart-items");
cartItemsDiv.innerHTML = "";
// Set the subtotal and total to $0
const subtotalSpan = document.getElementById("subtotal");
const totalSpan = document.getElementById("total");
subtotalSpan.innerHTML = "";
totalSpan.innerHTML = "$0";
// Remove the selected items from localStorage
localStorage.removeItem("selectedItems");
alert("Added items will be cleared.");
// Change the URL to the index page and prevent going to the checkout page
window.location.href = "sproduct6.html";
history.replaceState(null, "", window.location.href);
// Update the UI
document.getElementById("added-products").innerHTML = "You have no items in your cart!";
document.getElementById("buy-btn").style.display = "none";
document.getElementById("clear-button").style.display = "none";
if (cartItemCount == 0) {
setTimeout(function() {
alert("You have no items in your cart. Let's get back to product page.");
window.location.href = ('sproduct6.html');
}, 50); // 3 second delay
document.getElementById("added-products").innerHTML = "You have no items in your cart!";
continueButton.style.display = "none";
clearButton.style.display = "none";
// Save the visibility state of the buttons
localStorage.setItem("buttonsVisible", "false");
} else {
document.getElementById("added-products").innerHTML = "YOU ADDED THIS PRODUCTS";
}
}
if (storedCartItem) {
const cartItem = JSON.parse(storedCartItem); // Parse the storedCartItem string into an array
for (let i = 0; i < cartItem.length; i++) {
const cartItemElement = document.createElement("div");
cartItemElement.innerHTML = `
<hr />
<h3>${cartItem[i].title}</h3>
<p>Price: ${cartItem[i].price}</p>
<p>License: ${cartItem[i].license}</p>
<img src="${cartItem[i].image}" width='30%'/><br>
<audio controls style="width:50%;">
<source src="${cartItem[i].audio}" type="audio/mp3">
</audio>
`;
// ADD DELETE OPTION
cartItemsDiv.appendChild(cartItemElement);
const price = Number(cartItem[i].price.replace("$", "")); // Parse price as a number and remove dollar sign
subtotal += price;
// MAKE REPLACE TITLE TO YOU HAVE NO ITEMS IN YOUR CART
}
const subtotalElement = document.querySelector("#subtotal");
subtotalElement.textContent = `$${subtotal.toFixed(2)}`;
const totalElement = document.querySelector("#total");
const total = subtotal;
totalElement.textContent = `$${total.toFixed(2)}`;
// Add this line to redirect to index.html and pass the total as a query parameter
window.location.href = 'index.html?total=' + total.toFixed(2);
totalElement.textContent = `$${total.toFixed(2)}`;
const totalPriceInput = document.querySelector("#total");
totalPriceInput.value = total.toFixed(2);
passtotal(); // Call the function to pass the total price to the index page
function passtotal(){
var total = document.getElementById('total').value;
var subtotal = document.getElementById('subtotal').value;
localStorage.getItem("total", total);
return false;
}
}
</script>
and heres index code
<div class="sr-root">
<span id="total"></span>
<div class="sr-main">
<h1>Pay with a bunch of payment option</h1>
<form id="payment-form" method="POST">
<input type="text" name="email" id="email" placeholder="E-Mail" required>
<input type="text" name="name" id="name" placeholder="Full Name" required>
<div id="payment-element"></div>
<button>Pay</button><!--Make functional-->
<!--Make total price hidden and that total of this is same as in checkout and that its connected to ruby-->
<div id="error-messages"></div>
</form>
</div>
</div>
<script>
// get the value of the "total" parameter from the URL
const urlParams = new URLSearchParams(window.location.search);
const total = urlParams.get("total");
// set the text content of the span element to the total value
const totalSpan = document.getElementById("total");
totalSpan.textContent = total;
</script>
2
Answers
several things to look into, based on your code
#1 wrong tag hierarchy
you have the
<form>
inside the<div>
but you close the tag outside… it should be, for example#2 anchors surrounding buttons
you have
what are you trying to accomplish here? the
<a>
has a behavior already and you have a button inside it, that is of typesubmit
so you are assigning another behavior, try to only have thebutton
without surrounding it with ananchor
so you can expect the normal button behavior#3 how do form works?
you have a button of type
submit
that will submit theform
that surrounds this tag, in this case, your<form action="index.html" ...>
will be called and submitted, and it does that, it sends you to theindex.html
page as that’s what you are asking it, and in aGET
method (the default) meaning it will happened inputs to the URL instead of passing it in memory asPOST
does… but you do not have any inputs inside thatform
so it passes nothing, if you add an input, it will happend the value as you expect, likeit will send you to
index.html?total=200
#4 your index form
your button, is well placed without any anchor tag, but is a simple button with the default behavior, as you just have it as
<button>Pay</button>
this will style as a button, and will behave as a submityou also have it inside a form with the
POST
method, meaning you probably want it to send the data inside theform
in aPOST
manner, for that we usually do one of 2 things (though there are more ways to accomplish the same)the same as you did in the checkout form, we add the
type="submit"
and that will trigger theform
that has this button, to be triggeredwe add a javascript function or code that will run upon click, like
<button type="button" onclick="payNow()">Pay</button>
and in javascript it will run the function namedpayNow
that you should write in thescript
codewe had to tell the
button
that we want to treat it as a "dumb" button by specifying thetype="button"
or you will use the default behavior, and that tends to be whatever the implementation of each browser (web or mobile) have implemented, maybe it will act as atype="submit"
or it will act astype="button"
you do not know, and that is why we tend to set the expectation by using tetype
attribute on button tagsI hope this 4 tips can help you get "unstuck" and continue your code, keep it up and don’t give up, next month you will code this without even thinking about it 😊
Too much code. Isolate the lines relating to your question. In any case, do not nest a button in an anchor element. Your anchor element’s
href
should be programatically updated to include the query parameters that you want to pass, e.g.You can store the amount in localStorage though as well provided you are opening a page in the same origin/domain name.
Use the
URL constructor
.myurl.searchParams.append("dollar",12)
See https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams