How to add multiple Objects in Array in JavaScript? - javascript

Every time I click the "Add to Cart button" it will update the cartarray[]. What I want to do is to add a new object in the cart for every click so that I can have multiple objects for every different Cart item.
(function() {
const cartbtn = document.querySelectorAll(".add_to_cart_button");
cartbtn.forEach(function(btn) {
btn.addEventListener("click", function(event) {
if (event.target.parentElement.classList.contains("add_to_cart_button")) {
let fullpath = event.target.parentElement.previousElementSibling.children[0].children[0].src;
const item = {};
item.img = fullpath;
let name = event.target.parentElement.previousElementSibling.children[3].children[0].textContent;
item.name = name;
let price = event.target.parentElement.previousElementSibling.children[3].children[1].textContent;
let finalprice = price.slice(1).trim();
item.price = finalprice;
const cartarray = [];
var product = function(name, price, img) {
this.name = name
this.price = price
this.img = img
};
cartarray.push(new product(name, finalprice, fullpath));
console.log(cartarray);
}
});
});
})();
<div class="product-item men">
<div class="product discount product_filter">
<div class="product_image">
<img src="images/product_1.png" alt="">
</div>
<div class="favorite favorite_left"></div>
<div class="product_bubble product_bubble_right product_bubble_red d-flex flex-column align-items-center"><span>-$20</span></div>
<div class="product_info">
<h6 id="item-name" class="product_name">Fujifilm X100T 16 MP Digital Camera (Silver)</h6>
<div class="product_price">$520.00</div>
</div>
</div>
<div class="red_button add_to_cart_button">add to cart</div>
</div>

I leave an answer rather than a comment because I still don't have the reputation to leave a comment. Provide the HTML code, as my colleagues said and we'll be able to answer.
Something 'fishy' I notice that may stop your code to work are these two lines of code:
const cartbtn = document.querySelectorAll(".add_to_cart_button");
if (event.target.parentElement.classList.contains("add_to_cart_button"))
It may be the '.' in the first line, or missing in the second line which stops your code working. I may be wrong, it's just an assumption without seeing your full code

cartarray should be declared outside of the addEventListener in order for the items in the cart to be persistent.
I would also suggest to place the creation of the product outside as well, although technically this is not required.
See the following as an example where the for loop is simulating your button clicks:
const cartarray = [];
const product = function(name, price, img) {
return {
name: name,
price: price,
img: img
}
};
for (let x = 1; x < 6; x++) {
cartarray.push(new product('p' + x, x + '.00', 'path/to/img' + x + 'png'));
}
console.log(cartarray);

Related

Can anyone tell me why the DOM stops updating the order total in my restaurant app when I remove the LAST item in the array?

I'm working on a restaurant ordering app, and when I add items, it adds and removes them from the total display, but when I remove the FINAL item in the cart, the order total still shows the value of the last item that was removed. Here is a link to my code as well as the function itself that contain the order total:
https://codepen.io/vanessalearnsjavascript/pen/qBKGvQP?editors=0011
function handleOrderSection(){
let totalPriceArray = [];
let invoiceHtml = ``;
let totalPrice = 0;
orderList.forEach(function(chosenItem, index){
invoiceHtml += `
<div class="item-invoice">
<div class="remove-wpr">
<h3 class="item-invoice name">${chosenItem.name}</h3>
<button class="remove-btn" data-remove="${index}">Remove</button>
</div>
<h3 class="item-invoice-price">$${chosenItem.price}</h3>
</div>
`
//console.log(chosenItem)
totalPriceArray.push(chosenItem.price)
//console.log(totalPriceArray)
if(totalPriceArray.length >= 1){
let orderValue = totalPriceArray.reduce(function(total, num){
return total + num
})
console.log(orderValue)
let customOrder = ``
customOrder += `
<div id="order-total" class="total-display">
Order Total:$ ${totalPriceArray.reduce(function(total, num){
return total + num
})}
</div> `
document.getElementById("chosen-items").style.display = "block"
document.getElementById("chosen-items").innerHTML = customOrder
}
})
document.getElementById('ordered-items').innerHTML = invoiceHtml
if(orderList.length >= 1){
modal.style.display = "inline"
completeBtn.style.display = "inline"
} else {
modal.style.display = "none"
completeBtn.style.display = "none"
}
}
Any help is appreciated. Thanks in advance.
I've tried different things like adding the return statement to different parts of the function and even changing the event listeners, and it just continues to confuse me. I don't have too much to add to this part, just that it's been a real head scratcher for me.

click event listener method is not working on a specific div

I am trying to add an event listener to my "degree section div" but it is not working nor am I getting any errors. I have tried multiple ways of traversing the DOM to reach the "degree-section" div but to no avail.
Any kind of help is welcome and appreciated
Code:
let city = document.querySelector('#city');
let searchbtn = document.querySelector('.search-btn');
let city_name = document.querySelector('.city-name');
let temp = document.querySelector('.temp');
let feels_like = document.querySelector('.feels-like');
let humidity = document.querySelector('.humidity');
let locationIcon = document.querySelector('.weather-icon');
let checkbox = document.getElementById('celcius');
let weather_sec = document.querySelector('.weather-info');
let degree_section = weather_sec.firstElementChild;
let degree_section_span = degree_section.getElementsByTagName('span')[0];
//let wind = document.querySelector('.wind');
async function getUrl(city) {
try {
let theUrl = url + city + '&appid=' + apiKey;
let response = await fetch(theUrl, {
mode: 'cors'
})
let data = await response.json();
//Get data from api and change html content based on the recieved data
let temp_data = data.main.temp
temp.textContent = temp_data;
let feels_like_data = data.main.feels_like;
feels_like.textContent = feels_like_data + "K";
let humidity_data = data.main.humidity;
humidity.textContent = humidity_data;
let {
icon
} = data.weather[0];
locationIcon.innerHTML = `<img src="icons/${icon}.png">`;
//change K to C
degree_section.addEventListener('click', () => {
//logging a message just to check if it is working
console.log("c")
})
} catch (err) {
let error = document.createElement('span')
error.className = "error";
error.textContent = "Location does not exist"
let top_center_div = document.querySelector('.top-center')
top_center_div.appendChild(error)
city_name.textContent = "No city found"
}
}
searchbtn.addEventListener('click', (e) => {
let cityName = city.value;
city_name.textContent = cityName
console.log(cityName)
getUrl(cityName)
})
<body>
<div class="loc-container">
<div class="location">
<h1 class="city-name">City</h1>
<div class="weather-icon"><img src="icons/unknown.png" /></div>
</div>
</div>
<div class="weather-info">
<div class="degree-section">
<h2 class="temp">0.0</h2>
<span>K</span>
</div>
<div class="info-section">
<div class="info-flex">
<h3 class="feels-like">0K</h3>
<h4>Feels Like</h4>
</div>
<div class="info-flex">
<h3 class="humidity">0</h3>
<h4>Humidity</h4>
</div>
<div class="info-flex">
<h3 class="wind">0</h3>
<h4>Wind</h4>
</div>
</div>
</div>
<div class="top-center">
<div class="form">
<input type="text" name="city" id="city" required>
<label for="city" class="label-name"><span class="search-name">Search City...</span></label>
</div>
<!-- <i class="fas fa-search search-btn"></i> -->
<i class="material-icons search-btn" style="font-size: 35px;">search</i>
</div>
<script src="weather.js"></script>
</body>
This is what "data" looks like
{"coord":{"lon":72.8479,"lat":19.0144},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"}],"base":"stations","main":{"temp":303.14,"feels_like":303.45,"temp_min":301.09,"temp_max":303.14,"pressure":1014,"humidity":45},"visibility":2500,"wind":{"speed":3.09,"deg":120},"clouds":{"all":20},"dt":1638773692,"sys":{"type":1,"id":9052,"country":"IN","sunrise":1638754125,"sunset":1638793848},"timezone":19800,"id":1275339,"name":"Mumbai","cod":200}
Thank you in advance!
I believe the problem is with
let degree_section_span = degree_section.getElementsByTagName('span')[0];
since it selects the wrong element. Try changing it to
let degree_section_span = weather_sec.querySelector('.check');
and see if it works. You can also change the variable name to something more appropriate, while you're at it.
EDIT:
I think this is what you're trying to do. For the sake of siplicity , I removed everything not related to temp:
let target = weather_sec.querySelector("div.check"),
temp_data = data.main.temp;
temp.textContent = temp_data;
target.addEventListener('click', () => {
cel = parseInt(temp_data) - 273.15;
temp.textContent = cel.toFixed(2);
temp.nextElementSibling.textContent = "C";
});
So after 48hrs of debugging I finally figured out what is wrong. If you see in my HTML I have a div.top-center at the bottom. And due to some dimension issues in my css file the height of div.top-center spanned the entire page so essentially all of my divs were being wrapped inside div.top-center so even if I assigned a click event to my div.degree-section the target was always div.top-center and that is why the click event was not showing the proper output.

acces eventlistener in a created button in dom

edited with all the code, sorry for my messy coding, I am begginer
hope you can help with this,
I have just created a button in the dom with a function, I gave the button a class to apply an event listener, for some reason i am not able to activate the listener, does anyone have a clue about what I am doing wrong?
//this is th initial array of items, after I am changing it to an arrayof objects
let shoppingList = ['banana','apples','cherries','oranges', 'peaches'];
const list = document.querySelector('.list');
//this is the last thing I need, create new items and allow the del button
const foo=()=>{
console.log('hi');
}
const adder =(item, index, price,name)=>{
list.innerHTML += `<div class='item${[index+1]}'>${name}, price ${price} </div>`;
item[index]= {name,price};
const delElm = document.createElement('button');//the element to remove items
delElm.className = 'remove';
delElm.innerHTML = 'X';
list.appendChild(delElm);
const btndel = document.querySelector('.remove')
console.log(btndel)
btndel.addEventListener('click', foo)
}
//assign a random price to the original array
for (let i = 0; i < shoppingList.length; i++) {
let prices = i+Math.round((((Math.random()*5)+10))*100)/100;
let name = shoppingList[i];
adder(shoppingList,i,prices,name);
}
const btnElm= document.querySelector('.press');
//function to add new elements
const addItm=()=>{
const nameElm = document.querySelector('#text');
const priceElm = document.querySelector('#price');
let name = nameElm.value;
let prices = Number(priceElm.value);
let i = shoppingList.length-1;
adder(shoppingList, i, prices,name)
console.log(shoppingList)
}
console.log(shoppingList)
btnElm.addEventListener('click', addItm)
edit with the HTML, basically, the user can add new items filling the form, each item should be posible to be removed,
<input type="text" id="text" placeholder="name item">
<input type="text" id="price" placeholder="price">
<button class="press">add</button> -->
thanks you in advance

How can I remove an item from this cart?

I have created this cart by watching lots and lots of tutorials. Now I have come to remove an item from the cart. I would really appreciate if some one could help me out.
//add item to cart
(function(){
const cartbtn = document.querySelectorAll(".add_to_cart_button");
cartbtn.forEach(function(btn) {
btn.addEventListener("click", function(event){
if (event.target.parentElement.classList.contains("add_to_cart_button"))
{
let fullpath = event.target.parentElement.previousElementSibling.children[0].children[0].src;
const item = {};
item.img = fullpath;
let name = event.target.parentElement.previousElementSibling.children[3].children[0].textContent;
item.name = name;
let price = event.target.parentElement.previousElementSibling.children[3].children[1].textContent;
let finalprice = price.slice(1).trim( );
item.price = finalprice;
//console.log(item);
const cartitem = document.createElement('li');
cartitem.classList.add("clearfix");
cartitem.innerHTML =
`
<img src="${item.img}" alt="item1" />
<span class="item-name">${item.name}</span>
<span class="item-price">${item.price}$</span>
<span class="item-quantity"> <a href="#/" />Delete</span>
`;
const cart = document.getElementById("cartitem");
const insert =document.querySelector("insert");
cart.insertBefore(cartitem,insert);
showtotal();
}
});
});
function showtotal(){
const total =[];
const items = document.querySelectorAll(".item-price");
items.forEach(function(item){
total.push(parseFloat(item.textContent));
});
const totalmoney=total.reduce(function(total,item){
total += item;
return total;
},0);
const finalmoney = totalmoney.toFixed(2);
document.getElementById("totalitem").textContent=total.length;
document.getElementById("totalitems").textContent=total.length;
document.querySelector(".main-color-text").textContent = finalmoney ;
}
})();
At the code line,
<a href="#/" />Delete</span> // Also, do not forget to close Anchor Link tags
You can add a class, to these Delete buttons,
Delete
Add an event to your remove-item-from-cart classes when the page is fully loaded and in the event listener, use some JavaScript to delete item from cart by checking event variable.

Javascript (firebase): how can the firebase database key of a clicked item be obtained?

I have a firebase database structure like this
and I have a loop function
var jobTitle = document.getElementById('jobTitle');
var jobDescription= document.getElementById('jobDescription');
firebase.auth().onAuthStateChanged((user) => {
if (user) {
database = firebase.database();
var ref = database.ref('/Jobs/');
ref.on('value', gotData, errData);
}
})
var jobSnap = {};
function gotData(data) {
var date = Today;
var jobs = data.val();
var keys = Object.keys(jobs);
var container = document.getElementById('pos_1');
var container2 = document.getElementById('jobapp');
for (var i = 0; i<keys.length; i++) {
var k = keys[i];
var newCard = `
<li class="pos-card" id="pos_1">
<div class="content">
<div class="title new">`+jobs[k].JobTitle+`</div>
<div class="dept">Customer Service</div>
<div class="date">date</div>
<div class="refer">Apply</div>
</div>
<ul class="desc">
<li>`+jobs[k].JobSummary+`</li>
</ul>
</li>
`;
container.innerHTML += newCard;
}
}
function errData(err) {
console.log('Error!');
console.log(err);
}
This is the function that submits the application to the DB under the respective job id.
function newApplication() {
var database = firebase.database();
var applicant_Name = document.getElementById('name').value;
var applicant_Number = document.getElementById('phone').value;
var applicant_email = document.getElementById('email').value;
var AuthorId = firebase.auth().currentUser.uid;
var cover_letter = document.getElementById('cover_letter').value;
var JobId = jobSnap.key;
var postData = {
ApplicantName: applicant_Name,
ApplicantNumber: applicant_Number,
Applicantemail: applicant_email,
Author: AuthorId,
Cover_letter: cover_letter,
};
var newPostKey = firebase.database().ref().child('Applications').push().key;
var updates = {};
updates['/Applications/' + newPostKey] = postData;
updates[ JobId + '/Applications/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
that retrieves all entries in the database Jobs node and display them like this
When a user clicks the apply button on a job an application fades in; all the code that retrieves the Jobs and application are in the same html file. What I need to do is find a way to capture the firebase job key of the job that was clicked so that i can save the job application under the respective jobs. I have tried many methods but still no luck how can I implement this?
You'll need to keep track of the key of each item in the HTML. A common way to do that is by injecting it into the id attribute in the HTML:
var newCard = `
<li class="pos-card" id="${k}">
Then you can use the id when the user clicks on an element to find the item in the database.
A more idiomatic way to write your code would be:
function gotData(data) {
var date = Today;
var container = document.getElementById('pos_1');
var container2 = document.getElementById('jobapp');
data.forEach(function(jobSnap) { // loop over all jobs
var key = jobSnap.key;
var job = jobSnap.val();
var newCard = `
<li class="pos-card" id="${key}">
<div class="content">
<div class="title new">${job.JobTitle}</div>
<div class="dept">Customer Service</div>
<div class="date">${date}</div>
<div class="refer">Apply</div>
</div>
<ul class="desc">
<li>${job.JobSummary}</li>
</ul>
</li>
`;
container.innerHTML += newCard;
}
}
If the list is dynammic then you can assign it a unique id and add onclick listener
In your JS function,
Function name(value)
{
}

Categories

Resources