Poll Percentages in JavaScropt - javascript

Its a simple poll app in Js. where user vote count and percentages will change accordingly. But the problem i am facing is the percentages are not updated, lets say total vote is 5 and yes vote is 3 among them so yes vote percentage should be updates as the no votes comes along but it not been updated automatically.
let count = document.getElementById('count')
let ncount = document.getElementById('ncount')
let num = 0;
let nnum = 0;
document.getElementById('btn').addEventListener('click', () => {
let nper = document.getElementById('per')
num++
let total = num + nnum
let totalPercentages = num / total * 100
count.innerHTML = num + " " + "percentages" + totalPercentages + '%'
nper.innerHTML = nnum + num + '<div></div>' + "total vote cast"
})
document.getElementById('Nbtn').addEventListener('click', () => {
let per = document.getElementById('per')
nnum++
let total = num + nnum
let totalPercentages = nnum / total * 100
ncount.innerHTML = nnum + " " + totalPercentages + '%'
per.innerHTML = num + nnum + '<div></div>' + "total vote cast"
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<fieldset>
<legend>do you like pizza</legend>
<div id="count"> 0</div>
<button id="btn">yes</button>
<br></br>
<div id="ncount"> 0</div>
<button id="Nbtn">no</button>
<br></br>
<div id="per"></div>
</fieldset>
<script src="main.js"></script>
</body>
</html>

Using the event handlers as defined by the OP, the percentage updates can be handled in a separate function.
There are a few other updates to the code
statements should end with semicolons (;)
variables that are only assigned once should be declared with const
the <br> tag does not have a </br> closing tag
// const should be used for variables which are only assigned a value once
// every statement should end with a semicolon (;)
const count = document.getElementById('count');
const ncount = document.getElementById('ncount');
const per = document.getElementById('per');
let num = 0;
let nnum = 0;
// update the count, ncount and per displays
function updatePer() {
let total = num + nnum;
count.innerHTML = num + " percentages " + (num / total * 100) + '%';
ncount.innerHTML = nnum + " percentages " + (nnum / total * 100) + '%';
per.innerHTML = (nnum + num) + "<br>total vote cast";
}
// count each button click and call the updatePer function
document.getElementById('btn').addEventListener('click', () => {
num++;
updatePer();
})
document.getElementById('Nbtn').addEventListener('click', () => {
nnum++;
updatePer();
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<fieldset>
<legend>do you like pizza</legend>
<div id="count"> 0</div>
<button id="btn">yes</button>
<br>
<div id="ncount"> 0</div>
<button id="Nbtn">no</button>
<br>
<div id="per"></div>
</fieldset>
<script src="main.js"></script>
</body>
</html>

const poll = document.getElementById("poll");
// counts is an object literal which has two properties - yes and no
// yes and no are objects with an element and a count value
// these are used to keep track of the counts and update the corresponding element
const counts = {
yes: {
el: document.getElementById('yes-count'),
value: 0
},
no: {
el: document.getElementById('no-count'),
value: 0
}
};
const percentage = document.getElementById("percentage");
// get all the clicks in the poll
poll.addEventListener("click", evt => {
// get the id of the button that was clicked
if (evt.target.tagName === "BUTTON") {
const id = evt.target.id;
// remove '-btn' from the id
const count = id.replace('-btn', '');
// make sure the id is a property name
if (typeof counts[count] === "object") {
// get the counts object
const counter = counts[count];
// update the counter
counter.value++;
// update the display
counter.el.textContent = counter.value;
// update the percentage
percentage.textContent = ((counts.yes.value / (counts.yes.value + counts.no.value) * 100.0)).toFixed(2) + '%';
}
}
});
<fieldset id="poll">
<legend>do you like pizza</legend>
<output id="yes-count"> 0</output>
<button id="yes-btn">yes</button>
<br>
<output id="no-count"> 0</output>
<button id="no-btn">no</button>
<br>
<p>Percentage of people that like pizza <output id="percentage"></output></p>
</fieldset>

Related

The value is Incrementing instead of Decrementing in JavaScript?

I have a counter (up to 5) with Increment and Decrement Buttons the Thing is that When the maximum Limit of 5 is reached and I click the Decrement Button (minus Button) instead of going Down to 4 it goes up to 6 and After that it decrements Properly and this is the Same issue with the Increment Button.
So can anyone tell why this is happening and How to resolve it?
Any help is Highly Appreciated.
let increment = document.querySelector('.increment')
let decrement = document.querySelector('.decrement')
let text = document.querySelector('.text')
let addedAmount = document.querySelector('.added-amount')
let value = 1
function incre() {
if (value <= 5) {
let holder = value++
text.innerText = holder
let updatedEth = 0.25 * holder
addedAmount.innerText = updatedEth
} else {
alert('You can not take More than Five NFTs')
}
}
function decre() {
if (value >= 1) {
let holder = value--
text.innerText = holder
console.log(addedAmount.innerText - 0.25)
let minusedAmount = addedAmount.innerText - 0.25
addedAmount.innerText = minusedAmount
} else {
alert('you can not')
}
}
<div>
<button class="decrement" onclick="decre()">-</button>
<p class="text">0</p>
<button class="Increment" onclick="incre()">+</button>
</div>
<div>
<p><span class="added-amount"> 0.25 </span> eth</p>
</div>
You need to use the prefix operator to appear the result on click, also make the value as 0 in initialization otherwise the first value will be 2. you could remove the holder variable in this use case.
let increment = document.querySelector('.increment')
let decrement = document.querySelector('.decrement')
let text = document.querySelector('.text')
let addedAmount = document.querySelector('.added-amount')
let value = 0
function incre(){
if(value < 5){
text.innerText = ++value
let updatedEth = 0.25 * value
addedAmount.innerText = updatedEth
}else{
alert('You can not take More than Five NFTs')
}
}
function decre(){
if(value > 0){
text.innerText = --value
console.log(addedAmount.innerText - 0.25)
let minusedAmount = addedAmount.innerText - 0.25
addedAmount.innerText = minusedAmount
}else{
alert('you can not')
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<button class="decrement" onclick="decre()">
-
</button>
<p class="text">0</p>
<button class="Increment" onclick="incre()">
+
</button>
</div>
<div>
<p> <span class="added-amount"> 0.25 </span> eth</p>
</div>
</body>
</html>
Instead of pre/post decrementing the value, you can simply do text.innerText = holder-1; and then decrease value by 1.
let increment = document.querySelector('.increment')
let decrement = document.querySelector('.decrement')
let text = document.querySelector('.text')
let addedAmount = document.querySelector('.added-amount')
let value = 1
function incre(){
if(value <= 5){
let holder = value++
text.innerText = holder
let updatedEth = 0.25 * holder
addedAmount.innerText = updatedEth
}else{
alert('You can not take More than Five NFTs')
}
}
function decre(){
if(value >= 1){
let holder = value;
text.innerText = holder-1;
value -= 1;
console.log(addedAmount.innerText - 0.25)
let minusedAmount = addedAmount.innerText - 0.25
addedAmount.innerText = minusedAmount
}else{
alert('you can not')
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<button class="decrement" onclick="decre()">
-
</button>
<p class="text">0</p>
<button class="Increment" onclick="incre()">
+
</button>
</div>
<div>
<p> <span class="added-amount"> 0.25 </span> eth</p>
</div>
</body>
</html>

I'm doing my first small JavaScript project and I'm a bit stuck

I coded a simple game where you have to guess a random number. The user submits the number and the app compares it to the random generated number. The user gets back a message whether their number is bigger or smaller than the solution.
The Code is :
const start = document.getElementById("start")
const description = document.getElementById("description")
const gameBody = document.getElementById("root")
let valaszokHTML
start.addEventListener("click", gameStart)
function gameStart() {
gameBody.innerHTML = '<input type = "number" placeholder ="Enter your guess..." "min="1" max="1000" id="usernumber">' +
'</input>' + '<button id="guessbutton">This is my guess!</button>'
const guessSubmit = document.getElementById("guessbutton")
guessSubmit.addEventListener("click", compareNumbers)
}
function compareNumbers() {
let userNumber = document.getElementById("usernumber").value
if (myNumber.szamom > userNumber) {
gameBody.innerHTML += "<h1>Wrong! It's bigger than " + userNumber
} else if (myNumber.szamom < userNumber) {
gameBody.innerHTML += "<h1>Wrong! It's smaller than " + userNumber
} else if (myNumber.szamom == userNumber) {
gameBody.innerHTML = "<h1>Right! You won!</h1>"
}
}
const myNumber = {
szamom: Math.floor(Math.random() * 1000) + 1,
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="root">
<div id="description">
<h1> Try to guess the number between 1 and 1000!</h1>
</div>
<button id="start">Game start</button>
</div>
<script src="practice.js"></script>
</body>
</html>
So my problem that I can can only click the guessSubmit button once. The first time I click it creates the HTML I want, but then I can't use the button anymore. I want it to create a new h1 element whenever I click it (so it will be a bunch of h1 elements below/above each other, until the user gets the number)
Can you please help me and explain, what am I doing wrong?
I would be really appreciate to get some responses.
You have to add a addEventListener at the end of your compareNumbers function, because it is not global.
const start = document.getElementById("start")
const description = document.getElementById("description")
const gameBody = document.getElementById("root")
let valaszokHTML
start.addEventListener("click", gameStart)
function gameStart() {
gameBody.innerHTML = '<input type = "number" placeholder ="Enter your guess..." "min="1" max="1000" id="usernumber">' +
'</input>' + '<button id="guessbutton">This is my guess!</button>'
let guessSubmit = document.getElementById("guessbutton");
guessSubmit.addEventListener("click", compareNumbers);
}
function compareNumbers() {
let userNumber = document.getElementById("usernumber").value
if (myNumber.szamom > userNumber) {
gameBody.innerHTML += "<h1>Wrong! It's bigger than " + userNumber
} else if (myNumber.szamom < userNumber) {
gameBody.innerHTML += "<h1>Wrong! It's smaller than " + userNumber
} else if (myNumber.szamom == userNumber) {
gameBody.innerHTML = "<h1>Right! You won!</h1>"
}
let guessSubmit = document.getElementById("guessbutton");
guessSubmit.addEventListener("click", compareNumbers);
}
const myNumber = {
szamom: Math.floor(Math.random() * 1000) + 1,
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="root">
<div id="description">
<h1> Try to guess the number between 1 and 1000!</h1>
</div>
<button id="start">Game start</button>
</div>
<script src="practice.js"></script>
</body>
</html>
When you do gameBody.innerHTML += "some text" you're completely destroying and recreating all the content, hence eventListener of guessSubmit will be destroyed too. So maybe add some <h1 id="answer_text"></h1> and manipulate it's innerHtml

How do I use html user input as a javascript variable in my function?

I'm trying to create a dice rolling app that utilizes user input as the arguments for the function. I want to be able to enter the number of sides the dice should have, as well as how many dice should be rolled. For example, the user should be able to roll 5, 6-sided dice...or 2, 8-sides dice...etc...the two variables are up to the user to decide and input into the form. I've written some code with a "Dice Class" and a couple of functions which work when the two variables are hard coded. The problem is that for some reason the function cannot read the user input.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="dicex.css" />
<title>Dice</title>
</head>
<body>
<div class="container">
<form id="form" class="form" onsubmit="return false">
<h2>Dice Roller</h2>
<div class="form-control">
<input type="number" id="sides" placeholder="How many sides?" />
</div>
<div class="form-control">
<input type="number" id="quantity" placeholder="How many dice?" />
</div>
<div class="form-control">
<p id="results">My Results Go Here</p>
</div>
<button id="roll">Roll</button>
</form>
</div>
<script src="dice.js"></script>
</body>
</html>
Javascript
// Query Selectors
let sides = document.querySelector("#sides").value;
let quantity = document.querySelector("#quantity").value;
let results = document.querySelector("#results");
let roll = document.querySelector("#roll");
// Dice Class
class Die {
constructor(sides) {
this.sides = sides;
}
roll() {
let random_side = Math.floor(Math.random() * this.sides) + 1;
return random_side;
}
}
// Dice Roll Function
let create = function (e) {
let a = [];
for (let i = 0; i < 5; i++) {
let n = new Die(6);
let r = n.roll();
a.push(r);
}
let sum = a.reduce((a, b) => a + b);
results.textContent = `You rolled ${a} for a total of ${sum}!`;
e.preventDefault();
};
// Event Listeners
roll.addEventListener("click", create);
Use them inside the create function... which is triggered by an event.
// Query Selectors
//let sides = document.querySelector("#sides").value;
//let quantity = document.querySelector("#quantity").value;
let results = document.querySelector("#results");
let roll = document.querySelector("#roll");
// Dice Class
class Die {
constructor(sides) {
this.sides = sides;
}
roll() {
let random_side = Math.floor(Math.random() * this.sides) + 1;
return random_side;
}
}
// Dice Roll Function
let create = function (e) {
let a = [];
// Here
let sides = document.querySelector("#sides").value;
let quantity = document.querySelector("#quantity").value;
for (let i = 0; i < quantity; i++) { // use here
let n = new Die(sides); // and here
let r = n.roll();
a.push(r);
}
let sum = a.reduce((a, b) => a + b);
results.textContent = `You rolled ${a} for a total of ${sum}!`;
e.preventDefault();
};
// Event Listeners
roll.addEventListener("click", create);

'Bounce' in if else statement causing alert box to pop up more than once

I am designing a quiz that generates the question & answers dynamically each time, I have written an if-else statement to check if the answer is right but something isn't quite right. The increment score function doesn't work properly as random numbers are added and the alert box pops up more than once. It seems there is a bounce within the function but I can't figure out what it is.
// Game controls
const startButton = document.getElementById('start-button');
const quitButton = document.getElementById('quit-button');
const mainHeading = document.getElementById('main-heading');
const gameContainer = document.getElementById('game-container');
const scoreOutput = document.getElementById('score-total');
var questionCountOutput = document.getElementById('question-count');
let currentScore = 0;
let questionCount = 0;
startButton.addEventListener('click', startGame);
quitButton.addEventListener('click', quitGame);
const maxQuestions = 10;
const scoreValue = 20;
// Start game
function startGame(event) {
startButton.classList.add('hidden')
mainHeading.classList.add('hidden')
gameContainer.classList.remove('hidden')
questionCount = 0;
currentScore = 0;
generateQuestion()
};
// Quit Game
function quitGame(event) {
if (window.confirm('Are you sure you want to quit?')) {
gameContainer.classList.add('hidden')
startButton.classList.remove('hidden')
}
};
// Generates the questions
function generateQuestion() {
// Increment question count by 1 each time
questionCount++;
questionCountOutput.innerText = `${questionCount}`;
// variables to help generate question
let countriesCount = countriesList.length;
let randomNumber = getRandomInt(0, countriesCount);
let chosenCountry = (countriesList[randomNumber].country); // Generate random country from array
let correctAnswer = (countriesList[randomNumber].capital); // Generate the correct capital city from array
// Define correct answer
let isCorrectQuestionAnswer = {
question: chosenCountry,
option: correctAnswer
};
// Generate 3 random cities from capitalListOptions to act as other answer options
let answerOption1 = (countriesList[getRandomInt(0, countriesList.length)].capital);
let answerOption2 = (countriesList[getRandomInt(0, countriesList.length)].capital);
let answerOption3 = (countriesList[getRandomInt(0, countriesList.length)].capital);
// define option outputs to loop through
let optionOutputs = [{
'question': chosenCountry,
'option': correctAnswer
},
{
'question': chosenCountry,
'option': answerOption1
},
{
'question': chosenCountry,
'option': answerOption2
},
{
'question': chosenCountry,
'option': answerOption3
}
];
// Randomise the outputs so the correct answer isn't in the same place all the time
randomOptionOutputs = optionOutputs.sort(() => Math.random() - 0.5);
let buttonOutputs = '';
let i = 0;
// Loop through the options and retrieve their key values
//add key values to as button attributes
Object.keys(randomOptionOutputs).forEach(function(key) {
// Code to define the html for the buttons
buttonOutputs += '<button id="answer-' + i + '" data-answer="' + randomOptionOutputs[key]['option'] + '" data-country="' + randomOptionOutputs[key]['question'] + '" class="answer-btn" >' + randomOptionOutputs[key]['option'] + '</button>';
i++;
});
// Create the answer buttons and the questionText
document.getElementById('country-name').innerHTML = chosenCountry;
document.getElementById('answers-container').innerHTML = buttonOutputs;
// Loop through the buttons that have been created and add event listeners to them
for (let i = 0; i < 4; i++) {
document.getElementById("answer-" + i).addEventListener("click", function() {
checkAnswer(isCorrectQuestionAnswer)
});
};
};
// Generate random number to use as array index to generate questions and answers
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
};
// Checks if the answer selected is right, increments the score if it is, then moves on the to the next question
function checkAnswer(isCorrectQuestionAnswer) {
// Using a jquery method, retrieve the data-answer for the button clicked and compare this with the isCorrectQuestionAnswer object 'option'
$(document).on('click', '.answer-btn', function() {
var clickedButtonAnswer = $(this).data('answer');
// var clickedButtonQuestion = $(this).data('country');
if ((clickedButtonAnswer === isCorrectQuestionAnswer["option"])) {
$(this).addClass("correct");
incrementScore(scoreValue);
alert('Well done!!! You got that right');
generateQuestion();
return
} else {
$(this).addClass("incorrect");
alert("Ahhh that wasn't quite right - no worries, you'll get it next time!");
generateQuestion();
return
};
});
};
// function to increment the score with each new question
function incrementScore(num) {
currentScore += num;
scoreOutput.innerText = `${currentScore}`;
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../assets/css/style.css">
<title>Around the World!</title>
</head>
<body>
<div class="navbar-container">
<nav class="navbar-top">
<ul>
<li>
Home
</li>
<li>
Rules
</li>
<li>
Play Game
</li>
<li>
High Scores
</li>
</ul>
</nav>
</div>
<div class="title-container">
<h1 id="main-heading">Let's Play</h1>
</div>
<div id="start-game" class="container">
<button id="start-button" class="btn">Start Game</button>
</div>
<div id="game-container" class="hidden">
<div id="progress-container">
<p class="progress">Question <span id="question-count"></span> of 10</p>
</div>
<div id="score-container">
<p class="progress">Score: <span id="score-total">0</span></p>
</div>
<div id="questions-container" class="container">
<h2 class="question">What is the capital city of <span id="country-name">country name</span>?</h2>
</div>
<div id="answers-container" class="container">
</div>
<div id="quit-game" class="container">
<button id="quit-button" class="btn">Quit Game</button>
</div>
</div>
<script src="../assets/js/script.js" defer></script>
<script src="../assets/js/quiz.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>
</html>

JavaScript calculator writes wrong number

I have a small error in this code, please help me.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0,
maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>
<script type="text/javascript">
function calc() {
"use strict";
var price = document.getElementById('price').value;
var res = (price / 100 * 5 + 20) + price;
var show = document.getElementById('show').value = Math.floor(res);
}
</script>
</body>
</html>
ex:write 100 in input the result is 10025, I need 125
It's because you try to add String to a Number. You need to convert price to a Number like this :
var price = parseFloat(document.getElementById('price').value);
// Or like this :
var price = Number(document.getElementById('price').value);
// Or like this :
var price = document.getElementById('price').value * 1;
Full example which shows decimal numbers:
var priceElement = document.getElementById('price');
var showElement = document.getElementById('show');
function calc() {
var price = parseFloat(priceElement.value, 10);
var result = (price / 100 * 5 + 20) + price;
showElement.innerHTML = result.toFixed(2);
}
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>
Quite there.
A couple of fixes:
Store your elements outside of the function, since their ids won't change in your case:
var priceElement = document.getElementById('price');
var showElement = document.getElementById('show');
Use parseFloat(...) to parse floating point numbers stored in strings:
var price = parseFloat(priceElement.value);
To set an element's content (in your case, the content of the h1 element), use .innerHTML:
showElement.innerHTML = Math.floor(result);
var priceElement = document.getElementById('price');
var showElement = document.getElementById('show');
function calc() {
var price = parseFloat(priceElement.value);
var result = (price / 100 * 5 + 20) + price;
showElement.innerHTML = Math.floor(result);
}
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>
Yes, the value of price is string, so convert it to number.
And I don't think your "document.getElementById('show').value" is useful.
And the variable show is not used.
And the formula for res is somewhat convoluted -- see var v1.
Maybe you will find using console.log's useful in debugging.
<html>
<body>
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>
<script type="text/javascript">
"use strict";
function calc() {
var price = 1*document.getElementById('price').value;
console.log("price", price);
var res = (price / 100 * 5 + 20) + price;
console.log("res", res);
document.getElementById('show').innerHTML = Math.floor(res);
var v1 = price*1.05 + 20;
console.log("v1", v1);
document.getElementById('show').innerHTML += ", " + v1;
}
</script>
</body>
</html>

Categories

Resources