Shopping Cart and Calling Id/classes - javascript

ok I fixed most of my issues for my real estate project. The final problem I can't solve is my updateCartTotal Function. I get error message "Can not set property of Undefined at updateCartTotal" I have tried switching between querySelector and getElementsByClassName, taking the zeros out of my function, changing target elements, nothing seems to work. I know it might be something simple but I can't figure it out. HTML file below:
<section class="container content-section">
<h2 class="section-header">View Properties</h2>
<div id="propertyContainer" class="propertyItems1"></div>
</section>
<section class="container content-section">
<h2 class="section-header">CART</h2>
<div class="cart-row">
<span class="cart-item cart-header cart-column">Listing</span>
<span class="cart-avgPrice cart-header cart-column">PRICE</span>
<span class="cart-propType cart-header cart-column">Property Type</span>
<span class="cart-quantity cart-header cart-column">QUANTITY</span>
</div>
<div class="cart-items">
</div>
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price">$0</span>
</div>
<button class="btn btn-primary btn-purchase" type="button">PURCHASE</button>
</section>
This is the code I have for my js file:
//Recapture Data
let propertyItems1= document.getElementsByClassName(`#propertyItems1`);
let allItems = propertyContainer.getElementsByClassName(`fullAddress propType avgPrice`);
let data1 = [].map.call(allItems, fullAddress => fullAddress.textContent);
let data2 = [].map.call(allItems, propType => propType.textContent);
let data3 = [].map.call(allItems, avgPrice => fullAddress.textContent);
//Shopping Cart Functionality
if (document.readyState == 'loading') {
document.addEventListner('DOMContentLoaded', ready)
} else {
ready()
}
function ready() {
console.log("running the ready() function")
let removeItemButtons = document.getElementsByClassName('btn-danger')
for (let i = 0; i < removeItemButtons.length; i++) {
let button = removeItemButtons[i]
button.addEventListener('click', removeCartItem)
}
let quantityInputs = document.getElementsByClassName('cart-quantity-input')
for (let i = 0; i < quantityInputs.length; i++) {
let input = quantityInputs[i]
input.addEventListner('change', quantityChanged)
}
let addToCartButtons = document.getElementsByClassName('property-item-button')
for (let i = 0; i < addToCartButtons.length; i++) {
let button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
document.getElementsByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked)
}
function purchaseClicked() {
alert('Thank You for purchasing a home')
let cartItems = document.getElementsByClassName('cart-items')[0]
while(cartItems.hasChildNodes()) {
cartItems.removeChild(cartItems.firstChild)
}
updateCartTotal()
}
function removeCartItem(event) {
let buttonClicked = event.target
buttonClicked.parentElement.remove
updateCartTotal()
}
function quantityChanged(event) {
let input = event.target
if(isNaN(input.value) || input.value <= 0) {
input.value = 1
}
updateCartTotal()
}
function addToCartClicked(event) {
let button = event.target
let propertyItems1 = button.parentElement
let fullAddress = propertyItems1.querySelector('.fullAddress').innerText
let propType = propertyItems1.getElementsByClassName('propType').innerText
let avgPrice = propertyItems1.getElementsByClassName('avgPrice').innerText
addItemToCart(fullAddress,propType,avgPrice)
updateCartTotal()
}
function addItemToCart(fullAddress, propType, avgPrice) {
let cartRow = document.createElement('div')
cartRow.classList.add('cart-row')
let cartItems = document.getElementsByClassName('cart-items')[0]
let cartItemNames = cartItems.getElementsByClassName('cart-item-fullAddress')
for (var i = 0; i < cartItemNames.length; i++) {
if (cartItemNames[i].innerText == fullAddress) {
alert('This item is already added to the cart')
return
}
}
let cartRowContents = `
<div class="cart-item cart-column">
<span class="fullAddress">${fullAddress}</span>
<span class="propType">${propType}</span>
</div>
<span class="cart-avgPrice cart-column">${avgPrice}</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="1">
<button class="btn btn-danger" type="button">REMOVE</button>
</div>`
cartRow.innerHTML = cartRowContents
cartItems.append(cartRow)
cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem)
cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged)
}
function updateCartTotal() {
let cartItemContainer = document.getElementsByClassName('cart-items')[0]
let cartRows = cartItemContainer.getElementsByClassName('cart-row')
let total = 0
for (let i = 0; i < cartRows.length; i++) {
let cartRow = cartRows[i]
let avgPriceElement = cartRow.getElementsByClassName('cart-avgPrice')[0]
let quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
let avgPrice = parseFloat(avgPriceElement.innerText.replace('$', ''))
let quantity = quantityElement.value
total = total + (avgPrice * quantity)
}
total = Math.round(total * 100) / 100
document.getElementsByClassName('cart-total-avgPrice')[0].innerText = '$' + total
}
Please help my project is due very soon.

Your class for the cart-avgPrice is spelled wrong. Change
document.getElementsByClassName('cart-total-avgPrice')[0].innerText = '$' + total
to
document.getElementsByClassName('cart-avgPrice')[0].innerText = '$' + total

Related

Check if true or false on json parse into html

Currently have all data displaying perfectly except the boolean ones.
I have some data that if true or false they should display different html/css
So, how can I have a class or html that shows the data if returns true?
I'm a bit stuck on parsing this data on this code. As I was on the right direction until this new request.
The Json loooks like this:
{
"name": "Serena Gosling",
"supporterNumber": "0123456789",
"isStrongRelationship": true,
"ticketingPoints" :"2,500 Ticket Points",
"thumbnailUrl": "https://i.pravatar.cc/100"
},
fetch("supporters.json")
.then(response => response.json())
.then(supporters => {
localStorage.setItem("supporters", JSON.stringify(supporters));
});
let container = document.querySelector(".content");
let loadMoreButton = document.querySelector(".content button");
let initialItems = 4;
let loadItems = 2;
function loadInitialItems() {
let supporters = JSON.parse(localStorage.getItem("supporters"));
let out = "";
let counter = 0;
for (let supporter of supporters) {
if (counter < initialItems) {
out += `
<div class="supporter">
<h4 class="supporter__name">
<span class="supporter__thumbnail"></span>
${supporter.name}
${supporter.relationship}
<span class="supporter__number">(${supporter.supporterNumber})</span>
</h4>
<span class="supporter__points">${supporter.ticketingPoints}</span>
</div>
`;
}
counter++;
}
let div = document.createElement("div");
container.insertBefore(div, loadMoreButton);
div.innerHTML = out;
}
function loadData() {
let supporters = JSON.parse(localStorage.getItem("supporters"));
let currentDisplayedItems = document.querySelectorAll(".supporter").length;
let out = "";
let counter = 0;
for (let supporter of supporters) {
if (counter >= currentDisplayedItems && counter < loadItems + currentDisplayedItems) {
out += `
<div class="supporter">
<h4 class="supporter__name">
<span class="supporter__thumbnail"></span>
${supporter.name}
${supporter.relationship}
<span class="supporter__number">(${supporter.supporterNumber})</span>
</h4>
<span class="supporter__points">${supporter.ticketingPoints}</span>
</div>
`;
}
counter++;
}
let div = document.createElement("div");
container.insertBefore(div, loadMoreButton);
div.innerHTML = out;
div.style.opacity = 0;
if (document.querySelectorAll(".supporter").length == supporters.length) {
loadMoreButton.style.display = "none";
}
fadeIn(div);
}
function fadeIn(div) {
let opacity = 0;
let interval = setInterval(function() {
if (opacity <= 1) {
opacity = opacity + 0.1;
div.style.opacity = opacity;
} else {
clearInterval(interval);
}
}, 30);
}
loadInitialItems()
<div class="content">
<!-- content displaye from the javascript file -->
<button onclick="loadData()" class="load-more-button"><span>❭</span> </button>
</div>
You can use a ternary expression in the template literal.
out += `
<div class="supporter">
<h4 class="supporter__name">
<span class="supporter__thumbnail"></span>
${supporter.name}
${supporter.relationship}
<span class="supporter__number">(${supporter.supporterNumber})</span>
</h4>
<span class="supporter__points">${supporter.ticketingPoints}</span>
<span class="supporter__relationship">${supporter.isStrongRelationship ? "Strong" : "Weak"} relationship</span>
</div>
`;

How to delete an item from an array from localstorage onclick

I have the following code. It stores the info on localstorage each time the user clicks on an "add to cart" button:
let addCartItemButtons = document.getElementsByClassName('product-description-add')
for (let i = 0; i < addCartItemButtons.length; i++){
let button = addCartItemButtons[i]
button.addEventListener('click', addProduct)
}
function addProduct(event) {
let buttonClicked = event.target
let getTitle = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-title').innerText
let getImage = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-header img').src
let getColor = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li span').innerText
let getSize = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li select').value
let getPrice = buttonClicked.parentElement.parentElement.querySelector('.product-description-price').innerText
let getSpan = buttonClicked.parentElement.parentElement.querySelector('li span').getAttribute('id')
let oldItems = JSON.parse(localStorage.getItem('newProduct')) || [];
let newItem = {
'title': getTitle,
'image': getImage,
'color': getColor,
'size': getSize,
'price': getPrice,
'spanid': getSpan,
};
oldItems.push(newItem);
localStorage.setItem('newProduct', JSON.stringify(oldItems));
}
Then, i have a code that allows me to display the data the user have locally stored by creating divs and displaying the info:
let cartProducts = JSON.parse(localStorage.getItem("newProduct"))
for(let i = 0; i < cartProducts.length; i++){
let newCartProduct = document.createElement('div')
newCartProduct.classList.add('product')
newCartProduct.classList.add('cart')
const image = cartProducts[i].image
const title = cartProducts[i].title
const spanid = cartProducts[i].spanid
const color = cartProducts[i].color
const size = cartProducts[i].size
const price = cartProducts[i].price
let newCartProductContent = `
<div class="product-header cart"><img src="${image}" alt="" /></div>
<div class="product-content">
<h3 class="product-title" id="product-title">
${title}
</h3>
<div class="product-description">
<ul class="product-description-text cart">
<li>Color: <span id="${spanid}">${color} </span></li>
<li>Size: ${size} </li>
<li>Quantity: <input type="number" class="product-description-quantity" min="1" placeholder="2" value="2"></li>
</ul>
<p class="product-description-price" id="price1">
${price}
</p>
**Remove<i class="fas fa-trash"></i>**
</div>
</div>`
newCartProduct.innerHTML = newCartProductContent
let cartItems = document.getElementsByClassName('products_container_first-row')[0]
cartItems.append(newCartProduct)
}
So what i need to do now is to create a function that allows me to delete the data that it's the same which is on localstorage, each time that the user clicks on a "remove" button (in the above code is the line which has the ** ** at beginning and ending), but i cant figure out how to do this. Any ideas? Thanks!
UPDATE: i've come to this code but i get -1 as index for each element:
let addCartItemButtons = document.getElementsByClassName('product-description-add')
for (let i = 0; i < addCartItemButtons.length; i++){
let button = addCartItemButtons[i]
button.addEventListener('click', function(event){
let buttonClicked = event.target
let getTitle = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-title').innerText
let getImage = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-header img').src
console.log(getImage)
let getColor = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li span').innerText
let getSize = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li select').value
let getPrice = buttonClicked.parentElement.parentElement.querySelector('.product-description-price').innerText
let getSpan = buttonClicked.parentElement.parentElement.querySelector('li span').getAttribute('id')
console.log(getSpan)
let oldItems = JSON.parse(localStorage.getItem('newProduct')) || [];
let newItem = {
'id': i+1,
'title': getTitle,
'image': getImage,
'color': getColor,
'size': getSize,
'price': getPrice,
'spanid': getSpan,
};
oldItems.push(newItem);
localStorage.setItem('newProduct', JSON.stringify(oldItems));
})
}
let cartProducts = JSON.parse(localStorage.getItem("newProduct"));
for(let i = 0; i < cartProducts.length; i++){
let newCartProduct = document.createElement('div')
newCartProduct.classList.add('product')
newCartProduct.classList.add('cart')
console.log(newCartProduct)
const id = cartProducts[i].id
const image = cartProducts[i].image
const title = cartProducts[i].title
const spanid = cartProducts[i].spanid
const color = cartProducts[i].color
const size = cartProducts[i].size
const price = cartProducts[i].price
let newCartProductContent = `
<div class="product-header cart" id="${id}"><img src="${image}" alt="" /></div>
<div class="product-content">
<h3 class="product-title" id="product-title">
${title}
</h3>
<div class="product-description">
<ul class="product-description-text cart">
<li>Color: <span id="${spanid}">${color} </span></li>
<li>Size: ${size} </li>
<li>Quantity: <input type="number" class="product-description-quantity" min="1" placeholder="2" value="2"></li>
</ul>
<p class="product-description-price">
${price}
</p>
Remove<i class="fas fa-trash"></i>
</div>
</div>`
newCartProduct.innerHTML = newCartProductContent
let cartItems = document.getElementsByClassName('products_container_first-row')[0]
cartItems.append(newCartProduct)
}
function lsdel(storage_name, value){
if (localStorage.getItem(storage_name) === null) {
} else {
var ls_data = JSON.parse(localStorage.getItem(storage_name));
var index = ls_data.indexOf(value);
console.log("selected index:"+index);
if(index == -1){
// if not matched selected index
} else {
// is matched, remove...
ls_data.splice(index, 1);
localStorage.setItem(storage_name, JSON.stringify(ls_data));
console.log(ls_data);
}
}
}
value is the ID of an element, but ls_data is an array of objects, not IDs. So ls_data.indexOf(value) will not find the object in the array. And even if value were an object, this wouldn't work because object equality is based on identical objects in memory, not comparing contents.
You need to use findIndex to match the id property of an array element.
function lsdel(storage_name, value) {
if (localStorage.getItem(storage_name) === null) {} else {
var ls_data = JSON.parse(localStorage.getItem(storage_name));
var index = ls_data.findIndex(({id}) => id == value);
console.log("selected index:" + index);
if (index == -1) {
// if not matched selected index
} else {
// is matched, remove...
ls_data.splice(index, 1);
localStorage.setItem(storage_name, JSON.stringify(ls_data));
console.log(ls_data);
}
}
}

How to change quantity and remove items for a shopping cart application

I have a shopping cart application which I can currently add products to and remove them visibly but it does not update the total cost. I need to add this functionality and be able to update the quantity with some buttons which are in the display cart function. I tried using an onClick function but cant figure it out. Below is my JavaScript and a link to my application please let me know if you need any more information.
https://connorlewis128.github.io/ShoppingPage/Dist/product.html
In the cart there are three buttons an x which removes the products and two arrows for increaing and decreasing quantity.
remove buton
<i class="btn-remove fas fa-times-circle"></i>
increase
<span> <i class="fas fa-arrow-alt-circle-left btn-minus" ></i> </span>
decrease
<span> <i class="fas fa-arrow-alt-circle-right btn-plus"></i></span>
JS
let carts = document.querySelectorAll('#add-to-cart');
let favorites = document.querySelectorAll('#favorite');
console.log(favorites)
let products = [
{
name:'ZIPPERED HOODED SWEATSHIRT',
Tag:'https://connorlewis128.github.io/ShoppingPage/Dist/images/new%20product/black%20jacket/front.webp',
price:50.00,
inCart:0
}
]
// add to cart
for (let i =0; i < carts.length; i++) {
carts[i].addEventListener('click', () =>{
cartNumbers(products[i]);
totalCost(products[i])
})
}
function onLoadCartNumbers(){
let productNumbers =localStorage.getItem('cartNumbers');
if(productNumbers){
document.querySelector('span .navbarCart').textContent = productNumbers;
}
}
// Number of items added to cart
function cartNumbers(products) {
let productNumbers = localStorage.getItem('cartNumbers');
productNumbers = parseInt(productNumbers);
if(productNumbers){
localStorage.setItem('cartNumbers', productNumbers + 1) ;
document.querySelector('span .navbarCart').textContent = productNumbers + 1;
} else{
localStorage.setItem('cartNumbers',1) ;
document.querySelector('span .navbarCart').textContent = 1;
}
setItems(products);
}
// favorites
for (let i =0; i < favorites.length; i++) {
favorites[i].addEventListener('click', () =>{
favItems(products[i]);
totalCost(products[i])
})
}
function onLoadfavNumbers(){
let favNumbers = localStorage.getItem('favItems');
if(favNumbers){
document.querySelector('span .favoritesCount').textContent = favNumbers;
}
}
// number of favorites added
function favItems(products) {
let favNumbers = localStorage.getItem('favItems');
favNumbers = parseInt(favNumbers);
if(favNumbers){
localStorage.setItem('favItems', favNumbers + 1) ;
console.log(favNumbers)
document.querySelector('span .favoritesCount').textContent = favNumbers + 1;
} else{
localStorage.setItem('favItems',1) ;
document.querySelector('span .favoritesCount').textContent = 1;
}
setItems(products);
}
function setItems(products){
let cartItems = localStorage.getItem('productsInCart')
cartItems = JSON.parse(cartItems)
if(cartItems != null){
if(cartItems[products.Tag] == undefined){
cartItems = {
...cartItems,
[products.Tag]:products
}
}
cartItems[products.Tag].inCart +=1;
}
else{
products.inCart = 1;
cartItems = {
[products.Tag]:products
}
}
localStorage.setItem('productsInCart',JSON.stringify(cartItems));
}
function totalCost(products)
{
let cartCost =localStorage.getItem('totalCost');
if (cartCost != null){
cartCost = parseFloat(cartCost);
localStorage.setItem('totalCost', cartCost + products.price);
}
else{
localStorage.setItem('totalCost',products.price );
}
}
// display cart
function displayCart(){
let cartItems = localStorage.getItem('productsInCart');
cartItems = JSON.parse(cartItems);
console.log(cartItems);
let cartContainer = document.querySelector
(".products");
let cartCost =localStorage.getItem('totalCost');
if(cartItems && cartContainer){
cartContainer.innerHTML = '';
Object.values(cartItems).map(products => {
cartContainer.innerHTML += `
<div class="products">
<span>${products.name}</span>
<img src="${products.Tag}">
<i class="btn-remove fas fa-times-circle"></i>
<div class="productPrice"> $${products.price}</div>
<div class="productQuantity"> <span> <i class="fas fa-arrow-alt-circle-left btn-minus" ></i> </span> <span> ${products.inCart}</span><span> <i class="fas fa-arrow-alt-circle-right btn-plus"></i></span></div>
<div class="Total"> $${products.price * products.inCart}</div></div>
`
});
cartContainer.innerHTML += `
<section class="basketTotalContainer">
<h4 class="basketTotalTitle">
Basket Total:
</h4>
<h4 class="BasketTotal">
$${cartCost}.00
</h4>
</section>`
}
};
function removeItem(){
let removeItem = document.getElementsByClassName('btn-remove');
console.log(removeItem)
for (let i = 0; i < removeItem.length; i++){
let button = removeItem[i]
button.addEventListener('click',function(event){
console.log('clicked')
let removeItem = event.target
removeItem.parentElement.remove();
});
}}
// color change
function colorChange() {
showcase.style.animation = document.querySelector('input[name="colorradio"]:checked').value + ' 6s infinite';
}
// quantity change
function quantityChange() {
if(document.querySelector('btn-plus'))
{
products.inCart = products.inCart +1;
}
else if (document.querySelector('btn-minus')){
products.inCart = products.inCart - 1;}
}
onLoadCartNumbers();
onLoadfavNumbers();
displayCart();
removeItem();
quantityChange();
thanks for any help in advance!

comment appending on the first post only in Vanilla JavaScript

I am creating a status posting and commenting system.
It is implemented in Vanilla JavaScript. Anyone can add a post and can comment on the post.
Everything is working fine but the comment section is working on first post only.
deletion of comment and post is working fine.
I don't know what's the problem is, if anyone could help me..
Here is the HTML code
<div class="container-post" id="container-post">
<div class="create-post">
<form>
<div class="form-group">
<div class="username">
<p class="name" style="top:15px;">User Name</p>
</div>
<p class="qoutes">
<textarea style=" font-size: 15pt;" class="form-control" id="enter-post" rows="7" id="mypara" placeholder="Share Your Thoughts..."></textarea>
</p>
<div class="postbar">
<button type="button" class="btn btn-primary post-me" id="post-button"> <span id="postText">Post</span></button>
</div>
</div>
</form>
</div>
<hr class="line-bar">
<div class="allpost">
<div class="mainpost" id="post-div"></div>
</div>
Here is the JavaSCript code
showTask();
showComment();
let addPost = document.getElementById("enter-post");
let addPostBtton = document.getElementById("post-button");
addPostBtton.addEventListener("click", function () {
var addPostVal = addPost.value;
if (addPostVal.trim() != 0) {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
taskObj.push(addPostVal);
localStorage.setItem("localtask", JSON.stringify(taskObj));
}
showTask();
});
function showTask() {
let webtask = localStorage.getItem("localtask");
if (webtask == null) {
var taskObj = [];
}
else {
taskObj = JSON.parse(webtask);
}
let htmlVal = '';
let createPost = document.getElementById("post-div");
taskObj.forEach((item, index) => {
htmlVal += `
<div class="post-class"><div class="username u-name">
<p class="name i-name">${"User Name " + index}</p>
<i class="fas fa-trash-alt" onclick="removePost(${index});"></i></button>
</div>
<hr>
<p class="quotes">
${item}
</p>
<div class="comment-section" id="comment-section">
<p class="comment-qoute">
<textarea style=" font-size: 15pt;" class="form-control commentBox" rows="3" id="mypara" placeholder="Leave a comment"></textarea>
</p>
<button class="btn btn-primary comment-btn" id="commentBtn">comment</button>
<ul class="comments" id="comments-portion">
<p></p>
</ul>
</div>
</div>
<br><br>`
});
createPost.innerHTML = htmlVal;
}
function removePost(index) {
let webtask = localStorage.getItem("localtask");
let taskObj = JSON.parse(webtask);
taskObj.splice(index, 1);
localStorage.setItem("localtask", JSON.stringify(taskObj));
showTask();
}
var commentPost = document.getElementById('mypara');
var commentBtn = document.getElementById('commentBtn');
commentBtn.addEventListener('click', function () {
var commentValue = commentPost.value;
if (commentValue.trim() != 0) {
let commentTask = localStorage.getItem("comments");
if (commentTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentTask);
}
commentObj.push(commentValue);
localStorage.setItem("comments", JSON.stringify(commentObj));
}
showComment();
});
function showComment() {
let commentsTask = localStorage.getItem("comments");
if (commentsTask == null) {
var commentObj = [];
}
else {
commentObj = JSON.parse(commentsTask);
}
let commentHTMLValue = '';
var createComment = document.getElementById("comments-portion");
commentObj.forEach((item, index) => {
commentHTMLValue += `<div class="comment-box-btn">
<p>${index + ". "}<span>${item}</span></p>
<i class="far fa-times-circle fa-2x" onclick="removeComment(${index});"></i>
</div>
`;
});
createComment.innerHTML = commentHTMLValue;
}
var deleteBtn = document.querySelector('.comment-del');
deleteBtn.addEventListener('click', () => {
});
// remove comment
function removeComment(index) {
let commentTask = localStorage.getItem("comments");
let commentObj = JSON.parse(commentTask);
commentObj.splice(index, 1);
localStorage.setItem("comments", JSON.stringify(commentObj));
showComment();
}
When you use code like:
createComment.innerHTML = commentHTMLValue;
you are completely replacing the contents of the element. Try using:
createComment.innerHTML += commentHTMLValue;
which appends new content to the end of the existing contents.
I can't do a snippet here as the use of localStorage is not allowed. Copy this block into a blank file and save it as an html file and then open that in a browser.
This is how I think you are describing your requirements and is also based on the data format in my comments. It's not pretty and needs plenty of sprucing up, but it runs.
<!DOCTYPE html>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<html>
<head>
<title>Task listing</title>
<script type="text/javascript">
let taskList = [];
function checkTasks() {
let tasksList = getTasksList();
if (tasksList.length == 0) {
let newTask = prompt("Please enter a task description");
if (newTask) {
let thisIndex = getNewIndex();
let a = {"id": thisIndex, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
}
}
displayTasks();
}
function displayTasks() {
let container = document.getElementById("tasks");
container.innerHTML = "";
let taskList = getTasksList();
taskList.forEach(function(task){
let d = document.createElement("div");
d.id = "task_" + task.id;
d.className = "commentdiv";
d.innerHTML = "<h3>" + task.task + "</h3>";
let l = document.createElement("ul");
l.id = "comments_" + task.id;
let comments = task.comments;
if (comments.length > 0) {
let commentindex = 0;
comments.forEach(function(comment) {
let c = document.createElement("li");
c.innerHTML = comment;
let cb = document.createElement("button");
cb.id = "deletecomment_" + task.id + "_" + commentindex;
cb.innerHTML = "Delete comment";
cb.onclick = function() {deleteComment(task.id, commentindex);};
c.appendChild(cb);
l.appendChild(c);
})
}
let b = document.createElement("button");
b.id = "addcomment_" + task.id;
b.onclick = function() {addComment(task.id);};
b.innerHTML = "Add comment";
d.appendChild(b);
d.appendChild(l);
container.appendChild(d);
})
}
function addComment(taskid) {
let newcomment = prompt("Enter comment");
if (newcomment) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.push(newcomment);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
}
function addNewTask() {
let newTask = prompt("Enter task description");
let taskList = getTasksList();
let lastindex = localStorage.getItem("tasksindex");
let index = getNewIndex();
let a = {"id": index, "task": newTask, "comments": []}
taskList.push(a);
saveTasksList(taskList);
displayTasks();
}
function deleteComment(taskid, commentindex) {
let tasklist = getTasksList();
let filtered = tasklist.filter(task => task.id == taskid);
// as long as there is at least one task with the taskid value, find and delete the comment
// based on the index position of the comment in the comments array
if (filtered[0]) {
let thisTask = filtered[0];
thisTask.comments.splice(commentindex, 1);
let thisIndex = taskList.findIndex((task) => task.id == taskid);
taskList[thisIndex] = thisTask;
}
saveTasksList(taskList);
displayTasks();
}
function getTasksList() {
let tasks = localStorage.getItem("tasks");
taskList = JSON.parse(tasks);
if (!taskList) {
taskList = [];
}
return taskList;
}
function saveTasksList(taskList) {
localStorage.setItem("tasks", JSON.stringify(taskList));
}
function getNewIndex() {
let lastindex = localStorage.getItem("tasksindex");
let idx = 0;
if (!lastindex) {
idx = 1;
} else {
idx = Number(lastindex) + 1;
}
localStorage.setItem("tasksindex", idx);
return idx;
}
function removeAll() {
localStorage.removeItem("tasks");
localStorage.removeItem("tasksindex");
displayTasks();
}
window.onload = checkTasks;
</script>
<style type="text/css">
.commentdiv {
border:1px solid black;
width:1000px;
padding:5px;
border-radius:5px;
}
button {
margin-left:10px;
}
h3 {
width:100%;
border-bottom: 1px dotted black;
}
ul {
list-style-type:decimal;
}
</style>
</head>
<body>
<h2>My task list <button id="addNewTaskButton" onclick="addNewTask();">Add new task</button></h2>
<hr>
<div id="tasks">
</div>
<button id="removeAll" onclick="removeAll();">Remove all tasks</button>
</body>
</html>

Calculation not working when value with comma

Used below HTML & JS to calculate total value based on increment/decrement. It works fine if value without comma. 6300, 1200. When we add comma like 6,300 or 1,200. Below calculation method not working.
Hope i missed the logic to calculate with comma.. not sure which one i missed out.
let noofpaxinput = $('#txtnoofpax');
let intialvalue = 5;
let totalAmountValue = $('.grand-total .amount').html();
$('.noofpax').click(function(){
let packageamount = parseInt($('.package-amount .amount').html());
let perpersonamount = parseInt($('.per-person-cost').html());
let totalAmount = $('.grand-total .amount');
var txtnoofpaxValue = $(noofpaxinput).val();
if ($(this).hasClass('increasepax')){
$(noofpaxinput).val(parseInt(txtnoofpaxValue)+1);
$('.decreasepax').prop('disabled', false);
let getTotalnoofpax = parseInt($('#txtnoofpax').val());
let getDifferenceTotal = parseInt(getTotalnoofpax - intialvalue);
let perpersonamountTotal = perpersonamount * getDifferenceTotal;
let grandTotalAmount = parseInt(packageamount) + parseInt(perpersonamountTotal);
$('.perperson-amount .amount').html(perpersonamountTotal);
totalAmount.html(grandTotalAmount);
} else if ($(this).hasClass('decreasepax')){
if ((txtnoofpaxValue - 1) == intialvalue) {
$('.decreasepax').prop('disabled', true);
$(noofpaxinput).val(parseInt(parseInt(txtnoofpaxValue)-1));
} else {
$(noofpaxinput).val(parseInt(parseInt(txtnoofpaxValue)-1));
let getTotalnoofpax = parseInt($('#txtnoofpax').val());
let getDifferenceTotal = parseInt(getTotalnoofpax - intialvalue);
let perpersonamountTotal = perpersonamount * getDifferenceTotal;
let grandTotalAmount = parseInt(packageamount) + parseInt(perpersonamountTotal);
$('.perperson-amount .amount').html(perpersonamountTotal);
totalAmount.html(grandTotalAmount);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button-wrapper">
<button type="button" disabled="disabled" class="noofpax decreasepax">-</button>
<input id="txtnoofpax" type="text" value="5">
<button type="button" class="noofpax increasepax">+</button>
</div>
<div class="package-amount"><span>$</span><span class="amount">6,300</span></div>
<div class="fee-info--amount">
<div class="fee-info">
<div class="info">Every pax cost $<span class="per-person-cost">1,200</span></div>
</div>
<div class="fee-amount">
<div class="perperson-amount">
<span>$</span><span class="amount">0</span>
</div>
</div>
</div>
<div class="grand-total">
<p>Total Payable Amount</p>
<div class="fee-amount"><span>$</span><span class="amount">6,300</span></div>
</div>
You can simply use replace function to remove , comma with nothing. Your calculations will be perfect. Also, I would rec-emend using .text() not .html
When you use parseInt on a text or html and it has commas it will take the first value(character) which will be 1 in 1,200 and 6 in 6,300.
If you thinking of displaying the Total or Grand Total with commas added just use toLocaleString to show the number with commas added.
Demo
let noofpaxinput = $('#txtnoofpax');
let intialvalue = 5;
let totalAmountValue = $('.grand-total .amount').html();
$('.noofpax').click(function() {
let packageamount = $('.package-amount .amount').text().replace(',', '');
let perpersonamount = $('.per-person-cost').text().replace(',', '');
let totalAmount = $('.grand-total .amount');
var txtnoofpaxValue = $(noofpaxinput).val();
if ($(this).hasClass('increasepax')) {
$(noofpaxinput).val(parseInt(txtnoofpaxValue) + 1);
$('.decreasepax').prop('disabled', false);
let getTotalnoofpax = parseInt($('#txtnoofpax').val());
let getDifferenceTotal = parseInt(getTotalnoofpax - intialvalue);
let perpersonamountTotal = perpersonamount * getDifferenceTotal;
let grandTotalAmount = parseInt(packageamount) + parseInt(perpersonamountTotal);
$('.perperson-amount .amount').html(perpersonamountTotal.toLocaleString());
totalAmount.html(grandTotalAmount.toLocaleString());
} else if ($(this).hasClass('decreasepax')) {
if ((txtnoofpaxValue - 1) == intialvalue) {
$('.decreasepax').prop('disabled', true);
$(noofpaxinput).val(parseInt(parseInt(txtnoofpaxValue) - 1));
} else {
$(noofpaxinput).val(parseInt(parseInt(txtnoofpaxValue) - 1));
let getTotalnoofpax = parseInt($('#txtnoofpax').val());
let getDifferenceTotal = parseInt(getTotalnoofpax - intialvalue);
let perpersonamountTotal = perpersonamount * getDifferenceTotal;
let grandTotalAmount = parseInt(packageamount) + parseInt(perpersonamountTotal);
$('.perperson-amount .amount').html(perpersonamountTotal);
totalAmount.html(grandTotalAmount.toLocaleString());
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button-wrapper">
<button type="button" disabled="disabled" class="noofpax decreasepax">-</button>
<input id="txtnoofpax" type="text" value="5">
<button type="button" class="noofpax increasepax">+</button>
</div>
<div class="package-amount"><span>$</span><span class="amount">6,300</span></div>
<div class="fee-info--amount">
<div class="fee-info">
<div class="info">Every pax cost $<span class="per-person-cost">1,200</span></div>
</div>
<div class="fee-amount">
<div class="perperson-amount">
<span>$</span><span class="amount">0</span>
</div>
</div>
</div>
<div class="grand-total">
<p>Total Payable Amount</p>
<div class="fee-amount"><span>$</span><span class="amount">6,300</span></div>
</div>
You could use:
.replace(/,/g, '') to remove comma before parse
.toLocaleString() to print number with comma after calculation
let packageamount = parseInt($('.package-amount .amount').html().replace(/,/g, ''));
// ...
totalAmount.html(grandTotalAmount.toLocaleString());
let noofpaxinput = $('#txtnoofpax');
let intialvalue = 5;
let totalAmountValue = $('.grand-total .amount').html();
$('.noofpax').click(function(){
let packageamount = parseInt($('.package-amount .amount').html().replace(/,/g, ''));
let perpersonamount = parseInt($('.per-person-cost').html().replace(/,/g, ''));
let totalAmount = $('.grand-total .amount');
var txtnoofpaxValue = $(noofpaxinput).val();
if ($(this).hasClass('increasepax')){
$(noofpaxinput).val(parseInt(txtnoofpaxValue)+1);
$('.decreasepax').prop('disabled', false);
let getTotalnoofpax = parseInt($('#txtnoofpax').val());
let getDifferenceTotal = parseInt(getTotalnoofpax - intialvalue);
let perpersonamountTotal = perpersonamount * getDifferenceTotal;
let grandTotalAmount = parseInt(packageamount) + parseInt(perpersonamountTotal);
$('.perperson-amount .amount').html(perpersonamountTotal.toLocaleString());
totalAmount.html(grandTotalAmount.toLocaleString());
} else if ($(this).hasClass('decreasepax')){
if ((txtnoofpaxValue - 1) == intialvalue) {
$('.decreasepax').prop('disabled', true);
$(noofpaxinput).val(parseInt(parseInt(txtnoofpaxValue)-1));
} else {
$(noofpaxinput).val(parseInt(parseInt(txtnoofpaxValue)-1));
let getTotalnoofpax = parseInt($('#txtnoofpax').val());
let getDifferenceTotal = parseInt(getTotalnoofpax - intialvalue);
let perpersonamountTotal = perpersonamount * getDifferenceTotal;
let grandTotalAmount = parseInt(packageamount) + parseInt(perpersonamountTotal);
$('.perperson-amount .amount').html(perpersonamountTotal.toLocaleString());
totalAmount.html(grandTotalAmount.toLocaleString());
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button-wrapper">
<button type="button" disabled="disabled" class="noofpax decreasepax">-</button>
<input id="txtnoofpax" type="text" value="5">
<button type="button" class="noofpax increasepax">+</button>
</div>
<div class="package-amount"><span>$</span><span class="amount">6,300</span></div>
<div class="fee-info--amount">
<div class="fee-info">
<div class="info">Every pax cost $<span class="per-person-cost">1,200</span></div>
</div>
<div class="fee-amount">
<div class="perperson-amount">
<span>$</span><span class="amount">0</span>
</div>
</div>
</div>
<div class="grand-total">
<p>Total Payable Amount</p>
<div class="fee-amount"><span>$</span><span class="amount">6,300</span></div>
</div>

Categories