How to add numbers following a condition in JavaScript - javascript

I have a list of articles with different categories (ex: aaa, bbb, ccc). I want to display the sum of the data-prices for each category
For example, I should have 3.20 for aaa, 10.20 for bbb, and 11.20 for ccc
const nombrearticle = 7;
for (let i = 0; i < nombrearticle; i++) {
if (data - categorie === aaa) {
totalquantiteaaa += Number(data - prix);
} else if (data - categorie === bbb) {
totalquantitebbb += Number(data - prix);
} else if (data - categorie === ccc) {
totalquantiteccc += Number(data - prix);
}
}
<a style="cursor: pointer; " data-prix="2.10" data-qte="1" data-categorie="aaa" onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);">ajouter au panier</a>
<a style="cursor: pointer; " data-prix="1.10" data-qte="1" data-categorie="aaa" onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);">ajouter au panier</a>
<a style="cursor: pointer; " data-prix="3.10" data-qte="1" data-categorie="bbb" onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);">ajouter au panier</a>
<a style="cursor: pointer; " data-prix="4.10" data-qte="1" data-categorie="" onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);"> ajouter au panier</a>
<a style="cursor: pointer; " data-prix="5.10" data-qte="1" data-categorie="ccc" onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);">ajouter au panier</a>
<a style="cursor: pointer; " data-prix="6.10" data-qte="1" data-categorie="ccc" onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);">ajouter au panier</a>
<a style="cursor: pointer; " data-prix="7.10" data-qte="1" data-categorie="bbb" onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);">ajouter au panier</a>

It is not clear what part you are missing, and normally the thing to do would be to wait until you can be more specific.
I have time to kill, so I mocked up your problem. I believe that I have covered most likely issues: https://jsfiddle.net/eqr9jb5v/
details:
we need a total of prices. If that data is already in the javascript somewhere, use that instead, otherwise, we can gather it:
const categories = document.querySelectorAll('a[data-categorie]')
const totals = {}
for (let categorie of categories) {
if(!(categorie.dataset.categorie in totals)) totals[categorie.dataset.categorie] = 0
totals[categorie.dataset.categorie] += Number(categorie.dataset.prix)
}
it could be that instead your problem is really answering "how do I display this data to the user?". There are many ways to do it, but here is a pure javascript way:
we will create a mojunt point to display categories:
<div slot="categories"> </div>
and we will create a template so each categorie's price total can be displayed consistently:
<template id="categorie">
<section>
<header><h2>categorie - {categorie}</h2></header>
<p>total {sum}</p>
<section>
</template>
Now we can iterate over our categories, and apply each to our template, then mount it to our mount point:
Object.keys(totals).forEach(categorie => {
mountTotal({ categorie, sum: totals[categorie]})
})
function mountTotal({categorie,sum}) {
const fragment = template.content.cloneNode(true)
const node = document.importNode(fragment, true)
const title = node.querySelector('h2')
title.innerText = title.innerText.replace(/\{categorie\}/, categorie)
const content = node.querySelector('p')
content.innerText = content.innerText.replace(/\{sum\}/, sum)
mountPoint.appendChild(node)
}

There are many mistakes in your code. The first issue is that while comparing the aaa should be in double quotes. Also, you cannot get the properties of an "a" tag the way you are trying to get it.
Also, you are taking noofarticle as 7. Is it fixed for you? What if more element comes in?
Please look at my solution below.
<a style="cursor: pointer; " data-prix="2.10"data-qte="1" data-categorie="aaa"onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);">ajouter au panier</a>
<a style="cursor: pointer; " data-prix="1.10"data-qte="1" data-categorie="aaa"onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);">ajouter au panier</a>
<a style="cursor: pointer; " data-prix="3.10"data-qte="1" data-categorie="bbb"onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);">ajouter au panier</a>
<a style="cursor: pointer; " data-prix="4.10"data-qte="1" data-categorie=""onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);"> ajouter au panier</a>
<a style="cursor: pointer; " data-prix="5.10"data-qte="1" data-categorie="ccc"onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);">ajouter au panier</a>
<a style="cursor: pointer; " data-prix="6.10"data-qte="1" data-categorie="ccc"onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);">ajouter au panier</a>
<a style="cursor: pointer; " data-prix="7.10"data-qte="1" data-categorie="bbb"onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);">ajouter au panier</a>
<script>
// Get all the a tags
const a_tag = document.getElementsByTagName('a');
// you can further provide class to those a tags if you have other a tags as well
// const a_tag = document.getElementsByClassName('a-class');
// a-class is nothing but a simple css class.This will narrow down the elements to only the ones containing the class.
// Or you can use a query selector
let aaa = 0;
let bbb = 0;
let ccc = 0;
for (let index = 0; index < a_tag.length; index++) {
const element = a_tag[index];
let categorie = element.getAttribute('data-categorie');
if(categorie === 'aaa') {
aaa += Number(element.getAttribute('data-prix'));
}
if(categorie === 'bbb') {
bbb += Number(element.getAttribute('data-prix'));
}
if(categorie === 'ccc') {
ccc += Number(element.getAttribute('data-prix'));
}
}
console.log(aaa, bbb, ccc);
</script>
Running this code directly in a html file should give you your desired output.

Related

Issue with cart in JS/html [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 months ago.
Improve this question
I'm programming a cart system to add items and remove them, but I have a problem when removing items (it's not working).
Maybe someone can help me with it, that would be awesome.
gsdsd
gsdsd
gsdsdssd
gsdsd
gsdsd
gdds
gsdsd (without this wouldnt let me post)
gds
gdss
gdsd
Here is the code of the JS (sorry about the Spanish):
class Carrito {
//add product to cart
comprarProducto(e) {
e.preventDefault();
if (e.target.classList.contains('agregar-carrito')) {
const producto = e.target.parentElement.parentElement;
//read product data
this.leerDatosProducto(producto);
}
}
//read product data
leerDatosProducto(producto) {
const infoProducto = {
imagen: producto.querySelector('img').src,
titulo: producto.querySelector('h3').textContent,
precio: producto.querySelector('.precio span').textContent,
id: producto.querySelector('a').getAttribute('data-id'),
cantidad: 1
}
let productosLS;
productosLS = this.obtenerProductosLocalStorage();
productosLS.forEach(function(productoLS) {
if (productoLS.id === infoProducto.id) {
productosLS = productoLS.id;
}
});
this.insertarCarrito(infoProducto);
}
//show the item in cart
insertarCarrito(producto) {
const row = document.createElement('tr');
row.innerHTML = `
<td>
<img src="${producto.imagen}" width=100>
</td>
<td>${producto.titulo}</td>
<td>${producto.precio}</td>
<td>
</td>`;
listaProductos.appendChild(row);
this.guardarProductosLocalStorage(producto);
}
//it is suposed to delete the item visually not in the LocalStorage
eliminarProducto(e) {
e.preventDefault();
let producto, productoID;
if (e.target.classList.contains('borrar-producto')) {
e.target.parentElement.parentElement.remove();
producto = e.target.parentElement.parentElement;
productoID = producto.querySelector('a').getAttribute('data-id');
}
this.eliminarProductoLocalStorage(productoID);
this.calcularTotal();
}
//Empty the cart (not in LS)
vaciarCarrito(e) {
e.preventDefault();
while (listaProductos.firstChild) {
listaProductos.removeChild(listaProductos.firstChild);
}
this.vaciarLocalStorage();
return false;
}
//Saves items in LS
guardarProductosLocalStorage(producto) {
let productos;
//Toma valor de un arreglo con datos del LS
productos = this.obtenerProductosLocalStorage();
//Agregar el producto al carrito
productos.push(producto);
//Agregamos al LS
localStorage.setItem('productos', JSON.stringify(productos));
}
//check if there are items in the LS
obtenerProductosLocalStorage() {
let productoLS;
//Comprobar si hay algo en LS
if (localStorage.getItem('productos') === null) {
productoLS = [];
} else {
productoLS = JSON.parse(localStorage.getItem('productos'));
}
return productoLS;
}
//Shows items in LS
leerLocalStorage() {
let productosLS;
productosLS = this.obtenerProductosLocalStorage();
productosLS.forEach(function(producto) {
//Construir plantilla
const row = document.createElement('tr');
row.innerHTML = `
<td>
<img src="${producto.imagen}" width=100>
</td>
<td>${producto.titulo}</td>
<td>${producto.precio}</td>
<td>
</td>`;
listaProductos.appendChild(row);
});
}
//Deletes an item by id
eliminarProductoLocalStorage(productoID) {
let productosLS;
//Obtenemos el arreglo de productos
productosLS = this.obtenerProductosLocalStorage();
//Comparar el id del producto borrado con LS
productosLS.forEach(function(productoLS, index) {
if (productoLS.id === productoID) {
productosLS.splice(index, 1);
}
});
//Añadimos el arreglo actual al LS
localStorage.setItem('productos', JSON.stringify(productosLS));
}
//clears the localstorage
vaciarLocalStorage() {
localStor);
}
<div class="container">
<div class="header-menu">
<div class="hm-logo">
<a href="#">
<img src="img/jaf.logo.png" alt="">
</a>
</div>
<nav class="hm-menu">
<ul>
<li>Productos</li>
<li>Nosotros</li>
<li>Instagram</li>
<li>Contacto</li>
<li class="nav-item dropdown">
<i class="nav-link dropdown-toggle img-fluid las la-shopping-cart icono" height="100px" width="100px" href="#" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></i>
<span id="cant">0</span>
<div id="carrito" class="dropdown-menu" aria-labelledby="navbarCollapse">
<table id="lista-carrito" class="table">
<thead>
<tr>
<th>Imagen</th>
<th>Nombre</th>
<th>Precio</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
Vaciar Carrito
Procesar Compra
</div>
</li>
</ul>
</nav>
</div>
</div>
<!-- =================================
HEADER MENU Movil
================================= -->
<div class="header-menu-movil">
<button class="cerrar-menu"><i class="fas fa-times"></i></button>
<ul>
<li>Productos</li>
<li>Nosotros</li>
<li>Instagram</li>
<li>Contacto</li>
</ul>
</div>
html of a product:
<div class="product-item">
<div class="p-portada">
<a href="">
<img src="img/1.jpg" alt="">
</a>
<span class="stin stin-new">New</span>
</div>
<div class="p-info">
<a href="">
<h3>Example</h3>
</a>
<div class="precio">
<span>$0</span>
</div>
<a href="" class="hm-btn btn-primary uppercase agregar-carrito" data-id="2" >Add to cart</a>
</div>
</div>
Remove items from cart

How do I get the id of a button to be passed to and appended to a URL thus loading from a JSON?

When I click a button I want to pass that button poke.pid to add that to a URL to get some info;
The button
list = list + `<a href="#listing" id="${poke.pid}"
onclick="getPo('${poke.pid}')"
class="collection-item">${poke.name}</'a>`;
The code below is what I have;
async function getPo(url){
try {
let response = await fetch(url);
let result = await response.json();
displayPok(result);
} catch (e) {
console.log(e);
}
}
//the URL in question
getPokemon(('URL/somethinghere/').append('${poke.pid}'));
function displayPok(pok){
let result = document.querySelector('#result');
let html = ' ';
html = html +
`<div href="#result" id="${pok.pid}" class="card col m12 l10 offset-l1" style="margin-top: 20px">
<div class="card-image" >
<img class="teal" src="${pok.image}" alt="Bulbasaur Image">
</div>
<div class="card-content">
<span class="card-title"><p>${pokemon.name}</p></span>
<p> Type1: ${pok.type1}</p>
<p> Weight: ${pok.weight}</p>
<p> Height: ${pok.height}</p>
<a onclick="catchPokemon(1)" id="catchBtn" style="position:absolute;
right:15px; bottom:80px"
class="btn-floating btn-large waves-effect waves-light red">
<span class="iconify" style="font-size:40px; margin-top:8px" data-icon="mdi-pokeball" data-inline="false"></span>
</a>
</div>
</div>`;
result.innerHTML = html;
}
My question is when I click the button can I pas that pid by appending it to the url in question and thus load an item from the subsequent json?
If so how?
I found it:
//let response = await fetch(`https://pokedextr-api.herokuapp.com/pokemon/${pid}`);
//let result = await response.json();
let result = await sendRequest(`https://pokedextr-api.herokuapp.com/pokemon/${pid}`, 'GET');
Any one of the options above would work.

How can I get the ID of the clicked document and get the title and use/save it in firestore?

const setupProducts = (data) => {
if (data.length) {
let html = '';
data.forEach(doc => {
const product = doc.data();
const li = `
<li>
<div class="collapsible-header grey lighten-4"> ${product.title} </div>
<div class="collapsible-header grey lighten-4"> ${doc.id} </div>
<div class="collapsible-body white"> ${product.content}
<a href="" class="secondary-content">
<a class="btn orange modal-trigger" >Get ID</a>
</a>
</li>
`;
html += li;
});
productList.innerHTML = html
} else {
productList.innerHTML = '<h5 class="center-align">Login to view products</h5>';
}
};
My idea is that I want to get the ID by clicking on the document and then but the product.title in db.collection('activeWorks').doc(doc.id or product.id (I don't know what's right...)).set. I have no idea how to do this, please help
Maybe do something like this: set the id tag of each <li> element to the doc id from Firestore, then attach an onclick event trigger
const setupProducts = (data) => {
if (data.length) {
let html = '';
productList.innerHTML = ''
data.forEach(doc => {
const product = doc.data();
const li = `
<li id="${doc.id}">
<div class="collapsible-header grey lighten-4"> ${product.title} </div>
<div class="collapsible-header grey lighten-4"> ${doc.id} </div>
<div class="collapsible-body white"> ${product.content}
<a href="" class="secondary-content">
<a class="btn orange modal-trigger" >Get ID</a>
</a>
</li>
`;
html += li;
productList.innerHTML += html
document.getElementById(doc.id).onclick = () => {
// do firestore stuff here
// db.collection('activeWorks').doc(doc.id).set(your_data)
}
});
} else {
productList.innerHTML = '<h5 class="center-align">Login to view products</h5>';
}
};
If I misunderstood your question I'm sorry

How to dynamically change ID attribute using Vanilla JavaScript

I am currently building a to-do list app.
I am using the insertAdjacentHTML method to add new items to the list and that works just fine. My problem remains on how to dynamically change the id attribute that it begins to increase by 1 as I add a new item to the list.
How can I solve that?
Here is the code:
function addTaskFunc() {
const aTask = `
<div class="task" id="task-0">
<button class="done__btn">
<i class="far fa-check-square"></i>
</button>
<p>${box.value}</p>
<button class="priority">Make priority</button>
<button class="cancel__btn">
<i class="far fa-times-circle"></i>
</button>
</div>
`;
const x = box.value;
taskList.insertAdjacentHTML('afterbegin', aTask);
box.value = '';
}
newTask.addEventListener('click', addTaskFunc);
Add a counter (idCounter) and use it in the template literal, and increment it whenever you use it:
let idCounter = 0;
function addTaskFunc() {
const aTask = `
<div class="task" id="task-${idCounter++}">
<button class="done__btn">
<i class="far fa-check-square"></i>
</button>
<p>${box.value}</p>
<button class="priority">Make priority</button>
<button class="cancel__btn">
<i class="far fa-times-circle"></i>
</button>
</div>
`;
const x = box.value;
taskList.insertAdjacentHTML('afterbegin', aTask);
box.value = '';
}
You can use a variable that increments every time a new task is added.
This approach is slightly different because it provides a TaskBuilder constructor, this is only to avoid global variables and potential clashes with other scripts.
function TaskBuilder() {
if (!new.target) {
throw new Error("Illegal argument error, you should call this function as a constructor.");
}
this.currentId = 0;
}
TaskBuilder.prototype.addTask = function() {
const aTask = `
<div class="task" id="task-${this.currentId}">
<button class="done__btn">
<i class="far fa-check-square"></i>
</button>
<p>${box.value}</p>
<button class="priority">Make priority</button>
<button class="cancel__btn">
<i class="far fa-times-circle"></i>
</button>
</div>
`;
const x = box.value;
taskList.insertAdjacentHTML('afterbegin', aTask);
box.value = '';
this.currentId++;
};
const taskBuilder = new TaskBuilder();
newTask.addEventListener('click', function() {
taskBuilder.addTask();
});

remove selected option from drop-down available options

I have a drop-down and I need to remove the selected option and show the remaining options. thanks in advance
FacultyorStudent_Data: Array<string> = ['Faculty/Coach','Student']
selected_FacultyorStudent: string = this.FacultyorStudent_Data[0];
SelectFacultyorStudent(FnS){
this.selected_FacultyorStudent=FnS;
}
<div class="text-center" id="perf-type" *ngIf="section=='practice'">
<h4 class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-bar-chart" aria-hidden="true"></i>
<b>{{selected_FacultyorStudent}} <i class="fa fa-angle-down"
style="font-size: 0.7em; font-weight: 700;"></i></b> ·<small>beta v4</small>
</h4>
<ul class="dropdown-menu" style="width: 20%; left: 40%;color: #337ab7;">
<li *ngFor="let item of FacultyorStudent_Data; let i = index;" class="text-center"
[ngClass]="{'bg-selected-quiz': selected_FacultyorStudent==item}"
(click)="SelectFacultyorStudent(item)">
{{item}}</li>
</ul>
</div>
In your FacultyorStudent_Data array iterate it through loop , and match if item is equals to the item you want to remove.
If they match then remove it using splice method.
In you .ts file:
for(let i=0;i<this.FacultyorStudent_Data.length;i++){
if(FacultyorStudent_Data[i]=='yourItemName'){
this.FacultyorStudent_Data.splice(i,1)
}
}
if (FnS == 'Student'){
this.FacultyorStudent_Data.splice(0,1,'Faculty | Coach Insights')
}
else{
this.FacultyorStudent_Data.splice(0,1,'Student')
}
}

Categories