Pushing and popping values for each button click - javascript

On each button click, the value should be pushed into array and shown to the div.
If clicked again it should be popped out from array and removed from div as well.
I am toggling a Boolean value for this, but the popped values are not removed from the div when Boolean is false, perhaps something i am doing wrong.
Project can be edited here
$( "#button-list button" ).each(function(index) {
var items = [];
var toggle = false;
$(this).on("click", function(){
toggle = !toggle;
if(toggle === true)
items.push(this.value);
else
items.pop(this.value);
$("#results").append(items);
});
});
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button-list">
<button class="w3-button w3-black" value="(1,1)">(1,1)</button>
<button class="w3-button w3-black" value="(2,2)">(2,2)</button>
<button class="w3-button w3-black" value="(3,4)">(3,4)</button>
<button class="w3-button w3-black" value="(5,2)">(5,2)</button>
<button class="w3-button w3-black" value="(3,1)">(3,1)</button>
</div>
<p id="results"></p>

3 Small changes
Declare items outside of the each() function. If not it resets for each listener
Change the append() function for text().
Append will add the items on each click. You want to replace the items on each click.
pop() will remove the last element from the array. You need to use splice(). Splice recieves 2 values. First the index you want to remove, the the amount of element to remove.
using indexOf() we can get the element index on the array.
items.splice(items.indexOf(this.value), 1);
Hope this helps :)
var items = [];
$("#button-list button").each(function(index) {
var toggle = false;
$(this).on("click", function() {
toggle = !toggle;
if (toggle === true)
items.push(this.value);
else
items.splice(items.indexOf(this.value), 1);
//console.log(items);
$("#results").text(items);
});
});
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button-list">
<button class="w3-button w3-black" value="(1,1)">(1,1)</button>
<button class="w3-button w3-black" value="(2,2)">(2,2)</button>
<button class="w3-button w3-black" value="(3,4)">(3,4)</button>
<button class="w3-button w3-black" value="(5,2)">(5,2)</button>
<button class="w3-button w3-black" value="(3,1)">(3,1)</button>
</div>
<p id="results"></p>

var items = [];
$("#button-list button").on('click', function(e){
var indexOfElement = items.indexOf(e.target.value);
//value is not in the array
if (indexOfElement < 0) {
items.push(e.target.value);
} else {
//value is in the array, remove it
items.splice(indexOfElement, 1);
}
$('#results').text(items);
});
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button-list">
<button class="w3-button w3-black" value="(1,1)">(1,1)</button>
<button class="w3-button w3-black" value="(2,2)">(2,2)</button>
<button class="w3-button w3-black" value="(3,4)">(3,4)</button>
<button class="w3-button w3-black" value="(5,2)">(5,2)</button>
<button class="w3-button w3-black" value="(3,1)">(3,1)</button>
</div>
<p id="results"></p>

Related

Javascript button click listereners didn't redirect me to another page

i'm creating a shop cart and i started with a home page with 3 buttons
I had a little problem with redirecting those buttons to another pages
here's my html and javascript codes
I tried every possibility of redirection on javascript :(
function inscription(){
var myForm = "inscription-form.html";
document.getElementById("btn1f").addEventListener('click' , function () {
window.location.replace(myForm);
});
}
// redirect my second button
var myShop = "http://www.google.com";
document.getElementById("btn2s").addEventListener('click' , function () {
window.location.replace(myShop);
});
// redirect my third button
function redirect(){
var myGoogle = "http://www.google.com";
document.getElementById("btn3g").addEventListener('click' , function () {
window.location.replace(myGoogle);
});
}
<section class="body-container">
<div class="container-item title">
<h1>Who said women need therapy 😒,
<br> <br> We need shopping 🤑
</h1>
</div>
<div class="container-item buttons">
<div class="button-1">
<span>Create an account?</span>
<button type="button" class="btn" id="btn1f">Sign In</button>
</div>
<div class="button-2">
<span>You're a customer 😎</span>
<button type="button" class="btn" id="btn2s">Go Shopping</button>
</div>
<div class="button-3">
<span>Not Interested</span>
<button onclick="redirect()" type="button" class="btn" id="btn3g">Go Back</button>
</div>
</div>
</section>
<!-- html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<script src="js.js"></script>
</head>
<body>
<section class="body-container">
<div class="container-item title">
<h1>Who said women need therapy 😒,
<br> <br> We need shopping 🤑
</h1>
</div>
<div class="container-item buttons">
<div class="button-1">
<span>Create an account?</span>
<button type="button" class="btn" id="btn1f">Sign In</button>
</div>
<div class="button-2">
<span>You're a customer 😎</span>
<button type="button" class="btn" id="btn2s">Go Shopping</button>
</div>
<div class="button-3">
<span>Not Interested</span>
<button type="button" class="btn" id="btn3g">Go Back</button>
</div>
</div>
</section>
</body>
</html>
//below into js.js file
window.onload = function() {
var myShop = "http://www.google.com";
document.getElementById("btn2s").addEventListener('click' , function () {
window.location.href = myShop;
});
var myGoogle = "http://www.google.com";
document.getElementById("btn3g").addEventListener('click' , function () {
window.location.href = myGoogle;
});
var myForm = "inscription-form.html";
document.getElementById("btn1f").addEventListener('click' , function () {
window.location.href = myForm;
});
}
You have warpped the click listeners inside named functions and call those function onclick. So First time you click on a button the listeners is being attached and the second time, the listener will work (however second click also attachs another listener). So omit one of onclick or addEventListener one of them is enough. I prefer deleting named functions and onclick and just attach listeners (They should be attached at the end of document or after window load)
window.onload=function(){
var myForm = "inscription-form.html";
document.getElementById("btn1f").addEventListener('click' , function () {
window.location.replace(myForm);
});
var myShop = "http://www.google.com";
document.getElementById("btn2s").addEventListener('click' , function () {
window.location.replace(myShop);
});
// redirect my third button
var myGoogle = "http://www.google.com";
document.getElementById("btn3g").addEventListener('click' , function () {
window.location.replace(myGoogle);
});
}
<section class="body-container">
<div class="container-item title">
<h1>Who said women need therapy 😒,
<br> <br> We need shopping 🤑
</h1>
</div>
<div class="container-item buttons">
<div class="button-1">
<span>Create an account?</span>
<button type="button" class="btn" id="btn1f">Sign In</button>
</div>
<div class="button-2">
<span>You're a customer 😎</span>
<button type="button" class="btn" id="btn2s">Go Shopping</button>
</div>
<div class="button-3">
<span>Not Interested</span>
<button type="button" class="btn" id="btn3g">Go Back</button>
</div>
</div>
</section>

Display none if child and parent element have the same class

I have these menus around my horizontal scrolling site.
<section class="fun-stuff portfolio-cards" id="slide-1">
<div class="nav-list">
<button class="about">ABOUT</button>
<button class="fun-stuff">FUN STUFF</button>
<button class="home">HOME</button>
<button class="professional">PROFESSIONAL</button>
<button class="contact">CONTACT</button>
</div>
</section
The goal is to filter them based if the button classes have the same class as the ones in the section. If they have the same class (in this example 'fun-stuff') then that button will display:none.
My jQuery. I feel I'm close or totally over-complicating it.
jQuery(document).ready(function($) {
var theList = $('.nav-list button');
var i;
for (i=0; i < theList.length; i++){
var theButtons = '"' + theList[i].className + '"';
var parentClassName = theList[i].closest('section').className;
// tried this one. Was close i believe but no dice
if(theButtons = theList[i].closest('section').hasClass('"' + theButtons + '"') ){
// display that button as none
}
// tried this as well and for each button got 'no' in the console
if( $(theList[i].closest('section') ).hasClass(theButtons) ){
console.log('yes');
} else {
console.log ('no');
}
}
});
Yes you overdid it somewhat
$(function() {
$("button").each(function() {
var $parent = $(this).closest("section"), // the section wrapping the button
same = $parent.hasClass($(this).attr("class")); // parent has this button's class too
$(this).toggle(!same); // hide if the same (show if not)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="fun-stuff portfolio-cards" id="slide-1">
<div class="nav-list">
<button class="about">ABOUT</button>
<button class="fun-stuff">FUN STUFF</button>
<button class="home">HOME</button>
<button class="professional">PROFESSIONAL</button>
<button class="contact">CONTACT</button>
</div>
</section>
If you have more than one class on the button and you want to hide if one of them matches
$(function() {
$("button").each(function() {
var bList = this.classList,
parentList = $(this).closest("section")[0].classList, // the DOM element's classList
same = [...parentList] // convert to iterable
.filter(ele => bList.contains(ele)) // look up parent class in button classList
.length>0; // found?
$(this).toggle(!same);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="fun-stuff portfolio-cards" id="slide-1">
<div class="nav-list">
<button class="about">ABOUT</button>
<button class="fun-stuff bla">FUN STUFF</button>
<button class="home">HOME</button>
<button class="professional">PROFESSIONAL</button>
<button class="contact">CONTACT</button>
</div>
</section>
You can turn the section classes into a regular array, then filter and hide the buttons.
jQuery(document).ready(function($) {
var classes = $('#slide-1').attr("class").split(/\s+/);
classes.forEach(function (cls) {
$('.nav-list button').filter('.' + cls).hide()
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="fun-stuff portfolio-cards" id="slide-1">
<div class="nav-list">
<button class="about">ABOUT</button>
<button class="fun-stuff">FUN STUFF</button>
<button class="home">HOME</button>
<button class="professional">PROFESSIONAL</button>
<button class="contact">CONTACT</button>
</div>
</section>
You can do this pretty easily with vanilla Javascript:
const classNames = document.getElementById("slide-1").classList;
document.querySelectorAll(".nav-list > button").forEach((el) => {
if(classNames.contains(el.classList)){
el.style.display = "none";
}
});
<section class="fun-stuff portfolio-cards" id="slide-1">
<div class="nav-list">
<button class="about">ABOUT</button>
<button class="fun-stuff">FUN STUFF</button>
<button class="home">HOME</button>
<button class="professional">PROFESSIONAL</button>
<button class="contact">CONTACT</button>
</div>
</section>
Edit: Done with two lines of code:
const classList = document.getElementById("slide-1").classList;
document.querySelectorAll(".nav-list > button").forEach(el => el.style.display = classList.contains(el.classList) ? "none": "initial");
<section class="fun-stuff portfolio-cards" id="slide-1">
<div class="nav-list">
<button class="about">ABOUT</button>
<button class="fun-stuff">FUN STUFF</button>
<button class="home">HOME</button>
<button class="professional">PROFESSIONAL</button>
<button class="contact">CONTACT</button>
</div>
</section>

get the different values from button with same class name

I want to get the values from clicking the button with same class name, but whenever I clicked the button it shows undefined.
var clr;
const btn = document.querySelectorAll('.color');
function myFunction() {
for (var i = 0; i < btn.length; i++) {
clr = btn[i].value;
console.log(clr);
}
}
<div class="color">
<button class="btn" value="#BADA55" onclick="myFunction()"> Yellow </button>
<button class="btn" value="#10A426" onclick="myFunction()"> Green </button>
<button class="btn" value="#8787DE" onclick="myFunction()"> Purple </button>
</div>
const btn = document.querySelectorAll('.color'); gets the div not the buttons. Change that to const btn = document.querySelectorAll('.btn');:
var clr;
const btn = document.querySelectorAll('.btn');
function myFunction() {
for (var i = 0; i < btn.length; i++) {
clr = btn[i].value;
console.log(clr);
}
}
<div class="color">
<button class="btn" value="#BADA55" onclick="myFunction()"> Yellow </button>
<button class="btn" value="#10A426" onclick="myFunction()"> Green </button>
<button class="btn" value="#8787DE" onclick="myFunction()"> Purple </button>
</div>
If you only want the value from the button being clicked, then change your code to
function myFunction(btn) {
console.log(btn.value);
}
<div class="color">
<button class="btn" value="#BADA55" onclick="myFunction(this)"> Yellow </button>
<button class="btn" value="#10A426" onclick="myFunction(this)"> Green </button>
<button class="btn" value="#8787DE" onclick="myFunction(this)"> Purple </button>
</div>
do it in this way it will give you exact result
function myFunction(event) {
clr = event.target.value;
console.log(clr);
}
<div class="color">
<button class="btn" value="#BADA55" onclick="myFunction(event)"> Yellow </button>
<button class="btn" value="#10A426" onclick="myFunction(event)"> Green </button>
<button class="btn" value="#8787DE" onclick="myFunction(event)"> Purple </button>
</div>
First: scripting where scripting should be (no inline handlers). So add an event listener to the document, and let it check if the target (the element clicked) has classname btn. In that case: iterate through the an Array of elements with className btn (Array.from(document.querySelectorAll(".btn"))) using Array.forEach to display the values of those elements.
document.addEventListener("click", myFunction);
function myFunction(evt) {
console.clear();
if (evt.target.classList.contains("btn")) {
// a button.btn was clicked, so
let report = `You clicked button with value ${evt.target.value}. Other .btn values:`;
let values = [];
Array.from(document.querySelectorAll(".btn"))
.forEach(val => val !== evt.target && values.push(val.value));
console.log(`${report} ${values.join(", ")}`);
}
}
<div class="color">
<button class="btn" value="#BADA55"> Yellow </button>
<button class="btn" value="#10A426"> Green </button>
<button class="btn" value="#8787DE"> Purple </button>
</div>

How to know the button pressed among buttons in the div in Javascript

I have a div of 4 buttons, when I click on any button it redirects to the same page for all the buttons, I want to know which button the user has pressed before going to the next page, I've been trying, but couldn't find that.
Here is my code :
$( "#buttons" ).click(function() {
alert('button');
window.location.href = "score.html";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="countdown"></p>
<div id="buttons">
<button type="button" id="button1">button 1</button>
<button type="button" id="button2">button 2</button>
<button type="button" id="button3">button 3</button>
<button type="button" id="button4">button 4</button>
</div>
Do you have any idea
The element that the click started in is available as target on the event object passed into your handler, so (but see more below):
// Accept the event arg -------v
$( "#buttons" ).click(function(e) {
alert('button: ' + e.target.id); // <=== Use e.target.id to get its ID
// window.location.href = "score.html"; (commented out for live demo)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="countdown"></p>
<div id="buttons">
<button type="button" id="button1">button 1</button>
<button type="button" id="button2">button 2</button>
<button type="button" id="button3">button 3</button>
<button type="button" id="button4">button 4</button>
</div>
Note that that will do the alert whenever there's a click inside the #buttons div, even if it's not on a button. If you only want clicks on the buttons, you can use a selector with .on to only call you when the click went through a button. It will call your handler as though you had hooked the handler directly to the buttons, even though in fact you've hooked it to the #button div, and so we use this.id for the ID:
$( "#buttons" ).on("click", "button", function() {
alert('button: ' + this.id);
// window.location.href = "score.html"; (commented out for live demo)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="countdown"></p>
<div id="buttons">
<button type="button" id="button1">button 1</button>
<button type="button" id="button2">button 2</button>
<button type="button" id="button3">button 3</button>
<button type="button" id="button4">button 4</button>
</div>

add clicked value to stored value query

This is for a quiz. The user has a question with a choice of three answers. The answers are buttons. Each button has a value. When the user clicks the button, it gives a value then moves onto the next question. And this process repeats through a series of 7 questions. During this process, I want it to add each of the values clicked and have an accumulated total at the end.
I'm not sure if I should create a loop for this? I also want to note that this is being done without refreshing the page using .show and .hide features to the different sections of the quiz.
Thanks for your help!
Here are the buttons:
<button class="blue" id="goat" value="5">ANSWER 1</button>
<button class="blue" id="bird" value="10">ANSWER 2</button>
<button class="blue" id="fish" value="15">ANSWER 3</button>
function charValue () {
$(this).val();
}
var storedValue = $(this).$("button").data(charValue);
var accumValue = storedValue + charValue;
$("button").on('click', charValue);
You could add a final button at the end, for example:
<button id="finalbutton">Get Results</button>
And then create the javascript like so:
var accumValue = 0;
$("button").on('click', function() {
if(!$(this).attr('value')) {
return;
}
accumValue += parseInt($(this).attr('value'));
});
$('#finalbutton').on('click', function() {
alert(accumValue);
});
Try this:
$("button").click(function() {
var curScore = parseInt($("span").text(), 10);
var newScore = parseInt($(this).val(), 10);
$("span").text(curScore + newScore);
$(this).parent().hide();
$(this).parent().next().show();
});
.Question{display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="Question" style="display: block;">
<h3>Question 1</h3>
<button class="blue" id="goat" value="5">ANSWER 1</button>
<button class="blue" id="bird" value="10">ANSWER 2</button>
<button class="blue" id="fish" value="15">ANSWER 3</button>
</div>
<div class="Question">
<h3>Question 2</h3>
<button class="blue" id="goat" value="5">ANSWER 1</button>
<button class="blue" id="bird" value="10">ANSWER 2</button>
<button class="blue" id="fish" value="15">ANSWER 3</button>
</div>
<div class="Question">
<h3>Question 3</h3>
<button class="blue" id="goat" value="5">ANSWER 1</button>
<button class="blue" id="bird" value="10">ANSWER 2</button>
<button class="blue" id="fish" value="15">ANSWER 3</button>
</div>
<p>The final score is <span>0</span>
</p>
You can use .val() to get value and sum them.
To hide the current question after choose an answer, and show next one, use code:
$(this).parent().hide();
$(this).parent().next().show();
you can use below code and show sum at the end, DEMO here
var sum= 0;
$("button").click(function() {
sum = sum + parseInt($(this).val());
//alert(sum);
});
You can put all your questions on the same page.
As the user completes the questions, hide the completed questions and show the next unanswered question.
every time one answers a question, add the selected answer to your submission form. When the user finished all the questions show the submit button, and let one submit his answers.

Categories

Resources