Add specific items to cart on click - javascript

I want the cart to add the item that the Add to cart button relates to. Can you also please explain the reason behind it not working. Currently it is only adding the first product.
Here is the HTML:
<p class="name">Playstation 4 console (Black)</p>
<p class="pricetitle">Price: <span id="price">1899</span> AED</p>
<form>
<button type="button" onclick="addToCart()">Add to cart</button>
</form>
<p class="name">Xbox one console (Black)</p>
<p class="pricetitle">Price: <span id="price">1800</span> AED</p>
<form>
<button type="button" onclick="addToCart()">Add to cart</button>
</form>
and here is the JavaScript:
const name = document.querySelectorAll(".name");
const price = document.querySelectorAll("#price");
const button = document.querySelectorAll("button");
const cart = []
const addToCart = () => {
for (var i = 0; i < 1; i++) {
cart.push(name[i].innerText)
cart.push(parseInt(price[i].innerText))
}
console.log(cart)
}
Thank you

Here is an example, where we use data- attributes in the html. To help us when we load the cart.
let buttons = document.getElementsByTagName("button");
const cart = [];
for(var i=0; i<buttons.length; i++) {
let button = buttons[i];
console.log(button);
button.addEventListener('click', function(event){
console.clear();
console.log(event.target);
console.log(event.target.dataset.productSku);
cart.push( event.target.dataset.productSku );
console.log(cart)
});
}
<p class="name">Playstation 4 console (Black)</p>
<p class="pricetitle">Price: <span id="price">1899</span> AED</p>
<button data-product-sku="ps4black">Add to cart</button>
<p class="name">Xbox one console (Black)</p>
<p class="pricetitle">Price: <span id="price">1800</span> AED</p>
<button data-product-sku="xboxoneblack">Add to cart</button>
<div id="cart"></div>

Related

How can I insert elements in an array to a HTML document using Javascript?

I am trying to add the elements of a list called "taskList" made up of values I get from the input elements.
Can anyone please help me, I don't understand why the elements from the list are not showing.
var taskList = [];
var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');
button.onclick = function(){
var nHTML = '';
var userEnteredText = input.value;
taskList.push(userEnteredText);
taskList.forEach(function(task){
nHTML += '<li>'+task+'</li>';
});
document.getElementsByClassName('taskLists').innerHTML = '<ul>' + nHTML + '</ul>';
}
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button" >➕</button>
</div>
<div class="taskLists">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button type="button" class="button">Clear All</button>
</div>
</div>
I tried checking several times but nothing is updating in the HTML document
You shouldn't append to innerHTML, instead, use createElement to make the li, then set innerHTML of that new element to input.value and use appendChild to append it to the list
var input = document.getElementById('takeInput');
var button = document.getElementById('addInput');
var tlist = document.getElementsByClassName('taskLists')[0];
button.onclick = function(){
let e = document.createElement('li');
e.innerHTML = input.value
tlist.appendChild(e)
// Optionally, clear the input field to prevent double adding the same task
input.value = '';
}
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button" >➕</button>
</div>
<div class="taskLists">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button type="button" class="button">Clear All</button>
</div>
</div>
The main mistake was using .getElementsByClassName like it was one element only and not a list (don't ignore the s in elements!).
Anyway I slightly refactored your code to have better strategies for each of its goals and implemented also the logic for clearing the tasks list.
var taskList = [];
var input = document.getElementById('takeInput');
var buttonAdd = document.getElementById('addInput');
var buttonClear = document.getElementById('clearInput');
var tasksList = document.getElementById('tasksList');
buttonAdd.addEventListener('click', (event)=>{
addTask(input.value);
});
buttonClear.addEventListener('click', (event)=>{
tasksList = [];
document.querySelector('#tasksList ul').remove();
});
function addTask(value){
if(taskList.length == 0){
document.getElementById('tasksList').append( document.createElement('ul') );
}
taskList.push(value);
const newLI = document.createElement('li');
newLI.innerText = value;
document.querySelector('#tasksList ul').append(newLI);
}
<body>
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button">➕</button>
</div>
<div id="tasksList">
</div>
<div class="footer">
<span> You have <span class="pendingTasks"></span> tasks left </span>
<button id="clearInput" type="button" class="button">Clear All</button>
</div>
</div>
</body>
you just needed to use an ID on the tasklist.
getElementsByClassName needs an index, making your question a dupe of What do querySelectorAll and getElementsBy* methods return?:
document.getElementsByClassName('taskLists')[0].innerHTML
That said, here is a full version using recommended eventListener and IDs where relevant.
let tasks = [];
const taskList = document.getElementById('taskLists')
const input = document.getElementById('takeInput');
const add = document.getElementById('addInput');
const pendingTasks = document.getElementById('pendingTasks');
const clear = document.getElementById('clear');
const showTasks = () => {
taskList.innerHTML = `<ul>${tasks.map(task => `<li>${task}</li>`).join('')}</ul>`;
pendingTasks.textContent = `${tasks.length} task${tasks.length != 1 ? "s" : ""}`;
};
add.addEventListener('click', () => {
var userEnteredText = input.value;
tasks.push(userEnteredText);
showTasks();
});
clear.addEventListener('click', () => {
tasks = [];
showTasks();
});
taskList.addEventListener('click', (e) => {
const tgt = e.target.closest('li');
if (!tgt) return; // not a task
const task = tgt.textContent;
tgt.remove()
tasks = tasks.filter(currentTask => currentTask != task); // remove from list
showTasks()
});
showTasks(); //init
<div class="wrapper">
<header>To-Do List</header>
<div class="taskAdder">
<input id="takeInput" type="text" placeholder="Add your new To-Do">
<button id="addInput" class="button" type="button">➕</button>
</div>
<div id="taskLists"></div>
<div class="footer">
<span> You have <span id="pendingTasks"></span> left </span>
<button type="button" id="clear">Clear All</button>
</div>
</div>

create list item from input value

I'm working on a to-do list project and I got a problem, I want that when I click on the submit button the input value becomes a list item but it doesn't work.
here's the code:
let btn = document.getElementById('btn')
let txt = document.getElementById('txt')
btn.addEventListener('click', function(){
let list = document.createElement('li')
list.innerHTML = txt.value
})
<h1 id="title">To do list</h1>
<div class="main">
<input type="text" alt="type text here" id="txt">
<button type="submit" id="btn">Submit</button>
</div>
you forgot document.body.appendChild(list);
You need to have a ul (if it is to be an unordered list) element in your document - or to create one with JS, and then you need to add the new list items to that (not to the body).
Try this snippet (where the ul element is already in the document)
let btn = document.getElementById('btn')
let txt = document.getElementById('txt')
let ul = document.getElementById('ul');
btn.addEventListener('click', function() {
let list = document.createElement('li')
list.innerHTML = txt.value;
ul.appendChild(list);
})
<h1 id="title">To do list</h1>
<div class="main">
<input type="text" alt="type text here" id="txt">
<button type="submit" id="btn">Submit</button>
</div>
<ul id="ul">
</ul>

how to increase value with button click on javascript

I am learning javaScript. I have created a simple app, that when I click the button every time I want to increase the value.
let btn = document.querySelector(".btn");
btn.addEventListener("click", () => {
addCart();
});
function addCart() {
let btnn = (document.querySelector(".cart span").textContent = 1);
}
<ul class="cart">
cart
<span>(0)</span>
</ul>
<input type="button" value="click" class="btn" />
Add a count variable and increment it by one on every click:
let btn = document.querySelector(".btn");
let count = 0;
btn.addEventListener("click", () => {
addCart();
});
function addCart() {
count++;
document.querySelector(".cart span").textContent = `(${count})`;
}
<ul class="cart">
cart
<span>(0)</span>
</ul>
<input type="button" value="click" class="btn" />

Print all buttons in order of their click Javascript

I have 10 buttons 0-9. I want to print out all the numbers of the buttons in order of their 'click'. For example, If I click on buttons 5,4,3,2,1 then it should be printed like 54321 but with my coding it is printing in ascending order only. Can anybody help me figure this one out?
function nmbr0(){
var displaySpan = document.getElementById('result0');
displaySpan.innerHTML = 0;
}
function nmbr1(){
var displaySpan = document.getElementById('result1');
displaySpan.innerHTML = 1;
}
function nmbr2(){
var displaySpan = document.getElementById('result2');
displaySpan.innerHTML = 2;
}
<button type="button" onClick="nmbr0()"> 0 </button>
<button type="button" onClick="nmbr1()"> 1 </button>
<button type="button" onClick="nmbr2()"> 2 </button>
You have entered
<span id="result0"></span>
<span id="result1"></span>
<span id="result2"></span>
This is my output after clicking on 4321:
The problem is that the spans are already defined in ascending order, so even if you print 2 before 1, it'll still go inside the 'result2' span.
<span id="result0"></span>
<span id="result1"></span>
<span id="result2"></span>
How about this alternate instead?
<button type="button" onClick="print(this)"> 0 </button>
<button type="button" onClick="print(this)"> 1 </button>
<button type="button" onClick="print(this)"> 2 </button>
You have entered
<span id="displaySpan"></span>
<script>
var displaySpan = document.getElementById('displaySpan')
function print(button){
displaySpan.innerHTML += button.innerHTML
}
</script>
First, you don't have to create a function for each button number because you can use selector for that. Look a simple solution for that:
var element = "";
$("button").click(function() {
element += $(this).html(); //Get the button number
$("#result").html(element);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>0</button>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
<button>8</button>
<button>9</button>
<div>
<strong>You have entered:</strong> <span id="result"></span>
</div>
Your code was behaving unexpectedly becase you were using ids for each button text display, so the order was already predefined in them from 0-10.
You can append the numbers to the html itself like below
function nmbr(num){
var displaySpan = document.getElementById('numbers');
//appending one after another
displaySpan.innerHTML += num + ' ';
}
You have entered<br>
<span id="numbers"></span>
<br>
<button type="button" onClick="nmbr('0')"> 0 </button>
<button type="button" onClick="nmbr('1')"> 1 </button>
<button type="button" onClick="nmbr('2')"> 2 </button>
<button type="button" onClick="nmbr('3')"> 3 </button>
<button type="button" onClick="nmbr('4')"> 4 </button>
Using vanilla JavaScript :
function showButtonClicked ()
{
// Get the output node
let output = document.querySelector( '.output' );
// Get the buttons parent and add a click event on it
document.querySelector( '.buttons' ).addEventListener( 'click', () => {
// Get the clicked element
let target = event.target;
// If it is not a button, return
if ( target.nodeName !== 'BUTTON' ) return;
// Add the button number to the output
output.textContent += ` ${ target.textContent }`;
});
}
showButtonClicked();
<div class="buttons">
<button>0</button>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
<button>8</button>
<button>9</button>
</div>
<p>You have entered : </p>
<div class="output"></div>

Button Changes the Final Cost/Value

I've created few buttons, and when clicked I want to affect the final cost, working but not as it should be. The button has a value and the final value of cost doesn't work, can someone let me know what I'm doing wrong?
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].click) {
total += parseFloat(input[i].value);
}
}
document.querySelector(".priceText1").innerText = "$" + total.toFixed(2);
}
<div class="priceWrapper">
<h3 class="priceText1" id="total">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>
<div class="item">
<div class="itemProduct">
<h4 class="itemText">
<span class="no_selection">Logos</span>
</h4>
</div>
<div class="itemHidden">
<form action="" id="theForm">
<label>
<button class="buttonBg" name="product" value="25.00" type="button">Producto 3</button>
</label>
<label>
<button class="buttonBg" name="product" value="10.00" type="button">Producto 4</button>
</label>
</form>
</div>
But when I pick one, the final price won't work perfectly. is displaying a different number! can some help me?
Attach the click event to all the buttons and add the cost on every click like the snippet below shows.
NOTE : If you want to add the cost just one time by button you could disable the button immediately after the click using :
this.setAttribute('disabled','disabled');
Hope this helps.
var products = document.querySelectorAll(".buttonBg");
for (var i = 0; i < products.length; i++) {
products[i].addEventListener("click", totalIt);
}
function totalIt() {
var total = document.querySelector("#total");
var currentVal = parseInt( total.innerText );
var new_val = parseInt( this.value );
if( this.classList.contains('clicked') ){
total.innerText = ( currentVal - new_val ).toFixed(2);
}else{
total.innerText = ( currentVal + new_val ).toFixed(2);
}
document.querySelector("#total2").innerText = total.innerText;
this.classList.toggle('clicked');
}
.clicked{
color: green;
}
<div class="priceWrapper">
<h3 class="priceText1">$<span id="total">0.00</span></h3>
<h3 class="priceText2">Final Cost</h3>
</div>
<div class="item">
<div class="itemProduct">
<h4 class="itemText">
<span class="no_selection">Logos</span>
</h4>
</div>
<div class="itemHidden">
<form action="" id="theForm">
<label>
<button class="buttonBg" name="product" value="25.00" type="button">Producto 3</button>
</label>
<label>
<button class="buttonBg" name="product" value="10.00" type="button">Producto 4</button>
</label>
</form>
</div>
<h3 class="priceText1">$<span id="total2">0.00</span></h3>
I have adapted your code to make this work see below
Note below i have added id's to the product buttons.
<div class="priceWrapper">
<h3 class="priceText1" id="total">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>
<div class="item">
<div class="itemProduct">
<h4 class="itemText">
<span class="no_selection">Logos</span>
</h4>
</div>
<div class="itemHidden">
<form action="" id="theForm">
<label>
<button class="buttonBg" id="product1" name="product" value="25.00" type="button">
Producto 3
</button>
</label>
<label>
<button class="buttonBg" id="product2" name="product" value="10.00" type="button">
Producto 4
</button>
</label>
</form>
</div>
Then i have modified your code
//
// this will be the element clicked so just add it, as below
//
function addProduct() {
el = this;
total += parseFloat(el.value);
total_el.innerText = "$" + total.toFixed(2);
};
//
// Cache your total get a reference to the total element (faster!)
// when you write your code don't keep doing stuff when it can be done
// once - speed is everything and as you write more complex stuff
// doing it write from day one will pay off in your work (toptip)
//
var total = 0;
var total_el = document.querySelector(".priceText1");
//
// Bind up the click event
//
document.getElementById('product1').onclick = addProduct;
document.getElementById('product2').onclick = addProduct;
And here you can see the end result
https://jsfiddle.net/64v3n1se/
To scale this you would add the click handler using a class and a loop but for simpleness i have... kept it simple.
Because during your calculation you are getting all button's values and add them up so whenever the button is clicked you calculate the sum of the values of the buttons.
Your way of thinking right now, as far as I can tell, is wrong.
You can change your html code and script code like this.
With this way we are passing object of button to the function and we increase the global total variable within the function. Later on you change the dom.
var total = 0;
function totalIt(obj) {
total = total + parseFloat(obj.value);
document.querySelector(".priceText1").innerText = "$" + total.toFixed();
}
And pass the object of button in the html with
<button class="buttonBg" name="product" value="10.00" type="button" onclick="totalIt(this)">

Categories