How to update and save the variable after it has been changed? - javascript

I want to update the value of the counting variable after the words have been clicked, so they can be sorted from the highest clicked value from an array.
The variable value doesn't carry over to the next button.
I made the two variables as global variables in order to use it in other functions, but it doesn't seem to work and I also want the submit button to get updates after the user clicks the words after they have submitted once.
<h4> Communication </h4>
<button onclick="addressed()">addressed</button> ,
<button onclick="arbitrated()">arbitrated</button> ,
<br>-------------------
<p id="demo"> </p>
<p id="demo1"> </p>
<button onclick="myFunction()">Sort</button>
<p id="demo3"></p>
<script>
var countAddressed=0 ;
var countArbitrated=0;
var mostChosen = [
{word:"addressed:", selectedTimes:countAddressed},
{word:"arbitrated:", selectedTimes:countArbitrated}];
//set every buttons for action words
function addressed() {
countAddressed += 1;
//count how many individual action words there are.
document.getElementById("demo").innerHTML = "addressed: " + countAddressed;
}
function arbitrated() {
countArbitrated += 1;
//count how many individual action words there are.
document.getElementById("demo1").innerHTML ="arbitrated: " + countArbitrated;
}
function myFunction() {
mostChosen.sort(function(a, b){return b.selectedTimes - a. selectedTimes});
displayWords();
}
function displayWords() {
document.getElementById("demo3").innerHTML =
mostChosen[0].word + " " + mostChosen[0].selectedTimes + "<br>" + mostChosen[1].word + " " + mostChosen[1].selectedTimes + "<br>";
}
----I want this :
Communication
addressed(button) , arbitrated (button),
addressed: 3
arbitrated: 5
Sort(button)
addressed: 5
arbitrated: 3
----but I am getting this:
Communication
addressed , arbitrated ,
addressed: 3
arbitrated: 5
Sort
addressed: 0
arbitrated: 0

As I have mentioned in the comment, you are not updating mostChosen array when buttons are clicked.
// Update addressed count in addressed() function
mostChosen.forEach(token => {
if (token.word == 'addressed:') {
token.selectedTimes = countAddressed;
}
});
// Similar update is done in arbitrated() function
Here is the running code (your code, modified slightly) that modifies the array mostChosen:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Prescriptions</title>
</head>
<body>
<h4> Communication </h4>
<button onclick="addressed()">addressed</button> ,
<button onclick="arbitrated()">arbitrated</button> ,
<br>-------------------
<p id="demo"> </p>
<p id="demo1"> </p>
<button onclick="myFunction()">Sort</button>
<p id="demo3"></p>
<script>
var countAddressed = 0;
var countArbitrated = 0;
var mostChosen = [
{ word: "addressed:", selectedTimes: countAddressed },
{ word: "arbitrated:", selectedTimes: countArbitrated }];
//set every buttons for action words
function addressed() {
countAddressed += 1;
mostChosen.forEach(token => {
if (token.word == 'addressed:') {
token.selectedTimes = countAddressed;
}
});
//count how many individual action words there are.
document.getElementById("demo").innerHTML = "addressed: " + countAddressed;
}
function arbitrated() {
countArbitrated += 1;
mostChosen.forEach(token => {
if (token.word == 'arbitrated:') {
token.selectedTimes = countArbitrated;
}
});
//count how many individual action words there are.
document.getElementById("demo1").innerHTML = "arbitrated: " + countArbitrated;
}
function myFunction() {
mostChosen = mostChosen.sort(function (a, b) { return b.selectedTimes - a.selectedTimes });
displayWords();
}
function displayWords() {
document.getElementById("demo3").innerHTML =
mostChosen[0].word + " " + mostChosen[0].selectedTimes + "<br>" + mostChosen[1].word + " " + mostChosen[1].selectedTimes + "<br>";
}
</script>
</body>

Related

.toLowerCase() not working among other things not working

JS
var score = 0
var yes = "yes"
var pokemonName = [];
var bg = [];
var index = 0;
document.getElementById('repete').style.visibility = 'hidden';
(function asyncLoop() {
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
})();
function loop() {
var myAnswer = document.getElementById("myAnswer");
var answer = myAnswer.value;
if (answer.toLowerCase().trim() == pokemonName[num].toLowerCase().trim()) {
document.getElementById("text").innerHTML = "Correct, do you want to try again?";
score++
document.getElementById('repete').style.visibility = 'visible';
} else {
document.getElementById("text").innerHTML = "Incorrect, do you want to try again?" + "\n" + " The pokemon was " + pokemonName[num];
document.getElementById('repete').style.visibility = 'visible';
}
}
function loopRepete() {
var repete1 = document.getElementById("repete");
var replay = repete1.value;
if (replay.toLowerCase().trim() == yes.toLowerCase().trim()) {
asyncLoop();
} else {
document.getElementById("text").innerHTML = "Goodbye, your score is " + score;
location.href = 'index.html'
}
}
HTML
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Pokemon Quiz</title>
</head>
<body>
<lable> Answer </lable>
<input id="myAnswer" type="text">
<button onclick="loop()">click</button>
<p id="text"></p>
<div id="repete">
<lable> Answer </lable>
<input id="loop" type="text">
<button onclick="loopRepete()">click</button>
<p id="loopText"></p>
</div>
<script src="Gen3.js">
</script>
</body>
</html>
When I try take the input from the second second button (div id = repete) and put a toLowerCase() on it it does not work, and we I remove the toLowerCase() it still doesn't work but doesn't show a console error on the page. So I am confused On what I need to try do. I have tried to google it, but I could not find anything that helped.
You have to check if num exists in pokemonName array.
Otherwise, you'll be doing something like this:
[1,2,3][5].toLowerCase() which results in undefined.toLowerCase(), and you can't call .toLowerCase() on undefined as it only exists for String.
If you want asyncLoop to be defined you can't wrap it in a IIFE like that. I suspect you did that so it would run when the page loads, however there's another way to do that and still have the function defined for later use:
// define it like a normal function
function asyncLoop() {
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
}
// and call it right away
asyncLoop();

Why does JavaScript sometimes function not work when button is clicked?

I have a JavaScript voting system that has three buttons:
Vote Up, clear, and Vote Down
When I clicked the Vote Up button, it stays in zero. I have to press the Vote Up button several times to get it to vote up. Same with Vote down. When I pressed Clear, it does nothing.
Here is what I've done:
Assign function to Vote Up, and Vote Down and clear:
<button onclick="voteup()">
Vote Up
</button>
<button onclick="votedown()">
Vote Down
</button>
<button onclick="clear()">
Clear
</button>
Making a paragraph to display the result:
<p Id="vote">
You have 0 votes
</p>
Creating a global variable so I can access the variable on future functions:
var a = 0;
Creating the vote up functions:
function voteup() {
var b = a++;
Display the result in voteup() function:
document.getElementById('vote').innerHTML = "You have" + ' ' + b + "votes";
}
Making the second function (votedown):
function votedown(){
var b = a --;
document.getElementById('vote').innerHTML = "You have" + ' ' + b + "votes";
}
Create the function for clear:
function clear() {
document.getElementById('vote').innerHTML = "Your votes has been cleared";
}
I set the variable out of the function so voteup and votedown functions can access the a variable. I can't understand this.
var a = 0;
function voteup() {
a++;
document.getElementById('vote').innerHTML = "You have " + a + " votes";
}
function votedown() {
a--;
document.getElementById('vote').innerHTML = "You have " + a + " votes";
}
function clearVotes() {
document.getElementById('vote').innerHTML = "You have 0 votes";
var div = document.createElement("div");
div.innerText = "Your votes has been cleared."
div.style.color = "red";
div.style.transition = "opacity 0.25s ease-out"
document.body.appendChild(div)
setTimeout(function() {
div.style.opacity = "0";
setTimeout(function() {
div.remove()
}, 1000)
}, 3000)
a = 0
}
<button onclick="voteup()">
Vote Up
</button>
<button onclick="votedown()">
Vote Down
</button>
<button onclick="clearVotes()">
Clear
</button>
<p id="vote">
You have 0 votes
</p>
Also, you forgot a dot between document and getElementById in one of them.
Your code should be:
PS: it seems that clear is a reserved word that we cannot use as a function name
var a = 0;
const pVote = document.getElementById('vote');
function voteup() {
pVote.textContent = "You have " + ++a + " votes";
}
function votedown(){
pVote.textContent = "You have " + --a + " votes";
}
function doClear() {
a = 0
pVote.textContent = "Your votes has been cleared";
}
<button onclick="voteup()"> Vote Up </button>
<button onclick="votedown()"> Vote Down </button>
<button onclick="doClear()"> Clear </button>
<p id="vote"> You have 0 votes </p>
my way...
const p_vote = document.getElementById('vote')
, btVote = document.getElementById('bt-vote')
var voteCount = 0
btVote.onclick = e =>
{
if (!e.target.matches('button[data-op]')) return
voteCount = eval(`${voteCount} ${e.target.dataset.op}`)
p_vote.textContent = voteCount ? `You have ${voteCount} votes` : 'Your votes has been cleared'
}
#VoteBtns button { width : 10em; }
<div id="bt-vote">
<button data-op="+ 1" > Vote Up </button>
<button data-op="- 1" > Vote Down </button>
<button data-op="* 0" > Clear </button>
</div>
<p Id="vote" > You have 0 votes </p>
When using a-- the value of a is returned before the subtraction operation is executed. Thus, b is set only to the current value of a.
If you’d like this subtraction operation to occur prior to when the value is returned into b, use the decrement operator as a prefix (--a) instead.
The difference in prefix vs postfix of the decrement shorthand operator is clearly documented on its MDN page.

How do I display an unordered list in JavaScript?

I have to display a text field and a button “Generate times table”. When the user enters an integer from 1 to 9 and clicks the button, two duplicate times tables will appear side-by-side. However, the times tables on the right needs to be presented in an unordered list style.
When the user enters another number and click the button, the old times tables disappear and the new times tables will be generated accordingly.
I have managed to display one times tables set, however the second version (unordered list) won't display adjacent to it.
<html>
<head>
</head>
<body>
Enter integer:<input onClick="stopCounterAnimation()" id="number"
type="text">
<button onclick="startCounterAnimation()">Start Animation</button>
<button onclick="stopCounterAnimation()">Stop Animation</button>
<br/><br/>
<span id="counter"></span>
<script>
var counter = 0;
var counterSchedule;
var input = document.getElementById("number");
var counterSpan = document.getElementById("counter");
function startCounterAnimation() {
counterSchedule = setInterval(showCounter, 1000);
}
function showCounter() {
if (~~input.value) {
if (counter >= 9)
counter = 0;
counter++;
counterSpan.innerHTML = input.value + " X " + counter + " = "
+ eval(input.value + " * " + counter);
}
}
function stopCounterAnimation() {
clearInterval(counterSchedule);
input.value = "";
counter = 0;
}
</script>
</body>
</html>

setTimeout callback function not working

I am calling a function using onClick inside button. The called function is inside an object and it is getting called each second using setTimeout. But callback function is not getting called by setTimeout and works for just first call.
if i do not use object and use a encapsulating function that returns startPomadoro function, then its working.
###HTML Code ##########
<div class="cold-md-12 text-center">
<button>Set Pomodoro</button>
<input id="pomodoroInput" type="number">
<button>Set Break</button>
<input id="breakInput" type="number">
</div>
<div class="cold-md-12 text-center"><br>
<button onClick="pomodoroClock.startPomodoro()">Start Pomodoro</button>
</div>
<div id="output">
</div>
### JS COde
var pomodoroClock = {
countPomadoro: 0,
countBreak: 0,
currentTimerText:'',
startPomodoro: function(){
var pomadoroTimeInMinutes = document.getElementById('pomodoroInput').value;
var breakInMinutes = document.getElementById('breakInput').value;
if(this.countPomadoro<pomadoroTimeInMinutes){
var minutesLeftPomadoro = pomadoroTimeInMinutes - this.countPomadoro;
this.currentTimerText = "Your have " + minutesLeftPomadoro + " Minutes Left.";
this.countPomadoro++;
this.displayPomadoro();
setTimeout(this.startPomodoro, 1000);
}
else {
if(this.countBreak<breakInMnutes){
var minutesLeftBreak = this.breakInMinutes - this.countBreak;
currentTimerText = "Your have " + minutesLeftBreak + " Minutes Left in Break.";
this.countBreak++;
this.displayPomadoro();
setTimeout(this.startPomodoro, 1000);
}
else {
this.currentTimerText=" Break Time is UP. ";
this.displayPomadoro();
}
}
},
displayPomadoro: function(){
var pomodoroHtmlElement = document.createElement('p');
var outputDiv = document.getElementById('output');
pomodoroHtmlElement.textContent=this.currentTimerText;
outputDiv.appendChild(pomodoroHtmlElement);
}
}
You had a problem with this not being what you think, when function was called from setTimeout. Try something like this:
var pomodoroClock = {
countPomadoro: 0,
countBreak: 0,
currentTimerText: '',
startPomodoro: function() {
var that = this;
var pomadoroTimeInMinutes = document.getElementById('pomodoroInput').value;
var breakInMinutes = document.getElementById('breakInput').value;
if (this.countPomadoro < pomadoroTimeInMinutes) {
var minutesLeftPomadoro = pomadoroTimeInMinutes - this.countPomadoro;
that.currentTimerText = "Your have " + minutesLeftPomadoro + " Minutes Left.";
that.countPomadoro++;
that.displayPomadoro();
setTimeout(function() { that.startPomodoro() }, 1000);
} else {
if (that.countBreak < breakInMinutes) {
var minutesLeftBreak = that.breakInMinutes - that.countBreak;
currentTimerText = "Your have " + minutesLeftBreak + " Minutes Left in Break.";
that.countBreak++;
that.displayPomadoro();
setTimeout(function() { that.startPomodoro() }, 1000);
} else {
that.currentTimerText = " Break Time is UP. ";
that.displayPomadoro();
}
}
},
displayPomadoro: function() {
var pomodoroHtmlElement = document.createElement('p');
var outputDiv = document.getElementById('output');
pomodoroHtmlElement.textContent = this.currentTimerText;
outputDiv.appendChild(pomodoroHtmlElement);
}
}
<div class="cold-md-12 text-center">
<button>Set Pomodoro</button>
<input id="pomodoroInput" type="number">
<button>Set Break</button>
<input id="breakInput" type="number">
</div>
<div class="cold-md-12 text-center"><br>
<button onClick="pomodoroClock.startPomodoro()">Start Pomodoro</button>
</div>
<div id="output">
</div>
PS. You also had a typo breakInMnutes instead of breakInMinutes.
I have solved this problem by moving away from jquery , and simply
setting event handler on divs by wrapping each image inside one div using
JavaScript. Below is the sample code.
//code
handler.divs.forEach(function(div){
var img = document.getElementById(div);
img.onclick = function(){
var id = parseInt(img.id,10);
userPattern.push(id);
handler.effect(id);
console.log(" div clicked " + id + " u p " + userPattern);
if(userPattern.indexOf(id) !== simonGame.PATTERN.indexOf(id)){
console.log(" if ");
handleWrongInput();
} else if(userPattern.length === simonGame.PATTERN.length){
setTimeout(function(){simonGame.patternGen({result:"success"})},1200);
}
}
});
console.log(" up " + userPattern + " SGP " + simonGame.PATTERN);

Reset Function for dice rolling game

I have worked for a while on this code for learning purposes. I finally got the program to work, however when you "roll the dice", it only allows the dice to be rolled 1 time; If you wish to roll the dice a second time you must refresh the screen.
I am trying to build a reset function for this program so that I can roll the dice as many times as I wish without a screen-refresh.
I have built the reset function, but It is not working... It clear's the DIV's, but doesn't allow the program to be executed again.
Can someone please help me out?
*I am a semi-noobie at Javascript, I am making programs like this to practice my skills.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dice Rolling</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header>
<h1>Roll the Dice!</h1>
<h2>By: Jeff Ward</h2>
</header>
<h3>Setup your Dice!</h3>
<div id="left">
<form id="numberOfDiceSelection">
Number Of Dice Used:
<br>
<input id="numberOfDice" type="text" name="numberOfDice">
</form>
</div>
<div id="right">
<form id="diceSidesSelection">
Number of sides on each dice:
<br>
<input id="diceSides" type="text" name="diceSides">
</form>
</div>
<button type="button" onclick="roll()">Roll the Dice!</button>
<button type="button" onclick="reset()">Reset Roll</button>
<div id="output">
</div>
<div id="output1">
</div>
<script src="js/script.js"></script>
</body>
</html>
JavaScript:
function roll() {
var text = "";
var sides = +document.getElementById("diceSides").value;
var dice = +document.getElementById("numberOfDice").value;
var rolls = [];
// --------Ensures both Numbers are Intergers-----------
if (isNaN(sides) || isNaN(dice)) {
alert("Both arguments must be numbers.");
}
// --------Loop to Print out Rolls-----------
var counter = 1;
do {
roll = Math.floor(Math.random() * sides) + 1;
text += "<h4>You rolled a " + roll + "! ----- with dice number " + counter + "</h4>";
counter++;
rolls.push(roll);
}
while (counter <= dice)
document.getElementById("output").innerHTML = text;
// --------Double Determination-----------
var cache = {};
var results = [];
for (var i = 0, len = rolls.length; i < len; i++) {
if (cache[rolls[i]] === true) {
results.push(rolls[i]);
} else {
cache[rolls[i]] = true;
}
// --------Print amount of Doubles to Document-----------
}
if (results.length === 0) {} else {
document.getElementById("output1").innerHTML = "<h5> You rolled " + results.length + " doubles</h5>";
}
}
// --------RESET FUNCTION-----------
function reset() {
document.getElementById("output1").innerHTML = "";
document.getElementById("output").innerHTML = "";
document.getElementById("diceSides").value = "";
document.getElementById("numberOfDice").value = "";
text = "";
rolls = [];
}
Thank you!!
JSFiddle Link = https://jsfiddle.net/kkc6tpxs/
I rewrote and did what you were trying to do:
https://jsfiddle.net/n8oesvoo/
var log = logger('output'),
rollBtn = getById('roll'),
resetBtn = getById('reset'),
nDices = getById('numofdices'),
nSides = getById('numofsides'),
dices = null,
sides = null,
rolls = [],
doubles=0;
rollBtn.addEventListener('click',rollHandler);
resetBtn.addEventListener('click', resetHandler);
function rollHandler() {
resetView();
sides = nSides.value;
dices = nDices.value;
doubles=0;
rolls=[];
if(validateInput()) {
log('invalid input');
return;
}
//rolling simulation
var rolled;
while (dices--) {
rolled = Math.ceil(Math.random()*sides);
log('For Dice #'+(dices+1)+' Your Rolled: '+ rolled +'!');
rolls.push(rolled);
}
//finding doubles
//first sort: you can use any way to sort doesnt matter
rolls.sort(function(a,b){
return (a>b?1:(a<b)?0:-1);
});
for (var i =0; i < rolls.length; i++) {
if (rolls[i] == rolls[i+1]) {
doubles++;
i++;
}
}
if (doubles>0) log("You rolled " + doubles + " doubles");
}
function resetHandler(){
resetView();
nDices.value = nSides.value = '';
}
function resetView() {
getById('output').innerText = '';
}
function validateInput(){
return (isNaN(sides) || sides == '' || isNaN(dices) || dices == '');
}
function logger(x) { var output = getById(x);
return function(text){
output.innerText += text + '\n';
};}
function getById(x){ return document.getElementById(x); }

Categories