I have a javascript file and there is a function to calculate total and I want to use the calculated total value in javascript in my main HTML or php page what can I do? I tried using sessions but it did not work.
This is my javascript code. How can I get that total in my main page as a variable. I tried using getElementBy
function to but it did not work.
function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName('cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-row')
var total = 0
for (var i = 0; i < cartRows.length; i++) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementsByClassName('cart-price')[0]
var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
var price = parseFloat(priceElement.innerText.replace('$', ''))
var quantity = quantityElement.value
total = total + (price * quantity)
}
total = Math.round(total * 100) / 100
console.log(total)
document.getElementsByClassName('cart-total-price')[0].innerText = '$' + total
document.cookie ='total='+total+';expires=Wed, 1 Jan 2070 13:47:11 UTC; path=/'
//var x =document.cookie
console.log(x)
console.log(input)
}
javascript
function) to html( dom
) with dom-manipulation
term, example:document.getElementById("demo").innerHTML = "Your Data";
cookie
(not session
) and get it on server ( php
or whatever), example:document.cookie = "username=YOUR_DATA; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
xhttp.open("POST", "getinfo.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("data=yourData&other=another"); // pass data here
if your'e just looking to get the total into the "cart-price"
class name element the code below should work. I just changed anywhere you put element.getElementsByClassName('class-name')
to document.getElementsByClassName('class-name')
... html elements don't have a .getElementBy...
method attached to them
function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName('cart-items')[0]
var cartRows = document.getElementsByClassName('cart-row')
var total = 0
for (var i = 0; i < cartRows.length; i++) {
var cartRow = cartRows[i]
var priceElement = document.getElementsByClassName('cart-price')[0]
var quantityElement = document.getElementsByClassName('cart-quantity-input')[0]
var price = parseFloat(priceElement.innerText.replace('$', ''))
var quantity = quantityElement.value
total = total + (price * quantity)
}
document.getElementsByClassName('cart-total-price')[0].innerText = '$' + total
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.