"Score" variable not changing - javascript

I'm making an online game (a very simple one, it's my first) in JavaScript and HTML. It works fine, but there is a big problem. I want that whenever a particular image is clicked, 10 is added to the value of the variable score. Here is the code I used:
var score = 0;
function addScore() {
var test = parseInt(score);
var score = parseInt(test) + 10;
document.getElementById("score").innerHTML=score; }
And the images I want to have the functionality:
<img src='mole.png' alt='mole' onclick='addScore()' />
What's the problem and how do I fix it?

You can make your life little simpler by changing this:
1. Don't use the same varibale name in globally & locally.
2. Removing the `parseInt()` method as score is already an Integer.
So your final script would like to be:
var score = 0;
function addScore() {
score += 10;
document.getElementById("score").innerHTML=score;
}

You're shadowing the external score variable with the one of your function. And this internal variable is each time reset to 0.
Instead of parsing the score each time, simply initialize it once :
var score = 0;
function addScore() {
score += 10;
document.getElementById("score").innerHTML=score;
}

You declared score Globally and locally.So the value is not updating
var score = 0;
function addScore() {
var test = parseInt(score);
score = parseInt(test) + 10;
document.getElementById("score").innerHTML=score; }

Related

How do I add two variables intended to regularly update and get an up-to-date answer?

I'm trying to add two variables together. Both variables are intended to change regularly. No matter how they change, though, the third variable that's meant to be the two of them added together has either no value if the two aren't declared at the start, or remains as the sum of the starting values.
I put together a little demo thing to test it, with buttons that adapt the "prodScore" variable, and a button intended to update the "score" value to the sum of invisScore and prodScore.
<p>invisScore:<span id="invisScore"></span></p>
<p>prodScore:<span id="prodScore"></span></p>
<p>invisScore + prodScore:<span id="score"></span></p>
<p><button onclick="addProdScore()">Add 1 Production Score</button></p>
<p><button onclick="minusProdScore()">Minus 1 Production Score</button></p>
<p><button onclick="updateScore()">Update Score</button></p>
<script>
let invisScore = 5
let prodScore = 0
addProdScore = function(){
prodScore += 1
document.getElementById('prodScore').textContent = prodScore;
}
minusProdScore = function(){
prodScore -= 1
document.getElementById('prodScore').textContent = prodScore;
}
updateScore = function(){
document.getElementById('score').textContent = score;
}
var score = invisScore+=prodScore
</script>
This just gives me 5 every time, being the sum of the 0 value prodScore and the 5 value invisScore. What do I need to do to make the sum, "score" value be up to date?
The score variable is set once when the page loads and then never updated. You could update it when updating the values which calculate it, for example:
addProdScore = function(){
prodScore += 1;
score = invisScore+=prodScore;
document.getElementById('prodScore').textContent = prodScore;
}
Or perhaps make its calculation a function to be re-invoked when re-displaying the value:
updateScore = function(){
document.getElementById('score').textContent = score();
}
var score = function() {
return invisScore+=prodScore;
}
Basically, any way you look at it, if you want the "score" to be updated then you need to re-calculate it with the new values.
As an aside, I'm not sure this does exactly what you intend:
score = invisScore+=prodScore;
Are you also modifying invisScore here? For clarity you'd probably want to separate these operations into their own lines of code. As it stands, this line is confusing, and confusing code leads to bugs.

How does Javascript variable works?

Recently started learning Javascript.
Given an assignment for my class, to click a button (a number 10 is written on the button), and there has to be "Result = 55". (here all numbers from 0 to 10 are added)
To change words by clicking buttons, wrote code like this:
function myFunction(num) {
var p = document.getElementById("mydata");
for (var i = 0; i <= num; i++) {
sum = sum + i;
p.innerHTML = "Result = " + sum;
}
}
After submitting assignment for school, learned that had to add var sum = 0 above var p = document.getElementById("mydata")
However, do not understand what var sum = 0 means. As for looks already show when to begin and end calculating, feel like it doesn't have to be there.
var sum = 0; declares a local variable named sum, and sets its initial value to 0.
If you don't do this, when you do:
sum = sum + i;
the variable sum is initially undefined, and adding i to it results in NaN (Not a Number).
Some languages (e.g. PHP) automatically treat initialized variables as 0 in arithmetic expressions, but JavaScript doesn't do this, so you need to specify the initial value of the variable.
This has nothing to do with the way the for loop determines when to begin and end. It's about how to correctly add the numbers along the way.
It doesn't have to be before the p assignment, but it needs to be before the for loop.
Also, the line
p.innerHTML = "Result = " + sum;
doesn't need to be inside the loop. You should wait until the loop is done.

Variable doesn't work as it should

At first, my variable is set to zero. Then, after some questions answered correctly, the variable increases its value and it also shows me when I try it by alert(''). But when I try to write the variable as a text inside the HTML, it DOES show me, but I can't see increased number. I just see zero. It didn't even count to my variable. Can anyone explain me why? I'm posting a code here.
html:
<div class="textpadding">
<h1>
<center>
<font face ="Kozuka"><b><p id="hihi"></p></div></b></font>
</center>
</h1>
</div>
javascript:
var points = 0;
and down a bit, there's this command
document.getElementById("hihi").innerHTML = "Correct answers: " + points;
All these JavaScript things are inside the file.js. I don't know what's wrong with that.
javascript:
points = 0
var questions = 50;
function outoftime()
{
}
function opentest()
{
window.open("questions.html");
}
function checkanswers()
{
if(document.getElementById('3').checked)
{
points++;
}
if(document.getElementById('5').checked)
{
points++;
}
if(document.getElementById('10').checked)
{
points++;
}
window.open('resulteng.html');
}
document.getElementById("hihi").innerHTML = "Correct answers: " + points;
Try removing the 'var' in var points = 0 -> Should be just points = 0. That makes it a Global variable instead of a local one. I believe that that will do the trick.
if i were you,I'll create new class(completely optional),where the increment takes place each of the iteration .
inside you put post-increment factors:
(x=0;x<10;x++)
{
var = var+1 ;
}
just my two cents,others might have different thoughts.All the best mate .

How to increment a variable after button press

I was wondering how I could increase a variable when a button is clicked. here is my code. Can somebody point me in the right direction? thanks.
I am thinking when the button1 is clicked it will increase team 1's score by like 10, and will decrease if it is clicked again if that is necessary.
var Team2;
var Team2 == 0;
var Team1;
var Team1 == 0;
document.getElementById("calc").innerHTML = Team1;
function clicked(button1)
{
var team1 = team1 + 45
}
</SCRIPT>
<p>
Players for Team 1
First, the variable part: suppose you define a variable var value = 0. To increase it by 10, you can write value = value + 10, but in JavaScript this can be shorten to:
value += 10
The same way, to decrease it, just write value -= 10.
To call the function, you write onClick="someFunction()" (not the best practice), and then you define the function:
function someFunction(){
value += 10
};
This is the working fiddle: https://jsfiddle.net/gerardofurtado/6qh1yhsj/
If you want to see how to do the same thing without the onClick="someFunction()" part, here is a fiddle: https://jsfiddle.net/gerardofurtado/wff8mph3/
PS: I see that in your code you wrote var team2 == 0. In JavaScript, two equal signs make a comparison operator: http://www.w3schools.com/js/js_comparisons.asp
PS2: In JavaScript, you have to mind the scope. Once you defined the var team1, you can change it inside the function just by writing team1. But if you do as you did:
function someFunction(){
var team1 = team1 + 45
};
This team1 is not the same previous variable team1 defined outside the function. It's a different variable. And, as the team1 to the right of the equal sign is not defined, this will return a NaN (Not-A-Number).

Store score in a variable after an event

Desirable result: After the user choose an answer, I want to modify score variable in:
score += 1 if the answer is right either not changing at all if the answer is wrong.
Current result: For every choice user is making, the score remains the same: 0.
First, I store the paragraph that will be changed in question_paragraph and the button that will be clicked by user in next_button. Also, I stored the value(I put the attribute value on every input using the array notation - 0 first, 1 second etc.) in user_answer.
var question_paragraph = document.getElementById('question');
var next_button = document.getElementById('next');
var i = 0;
var user_answer = getCheckedValue(document.getElementsByName('choice'));
var y = 0;
var score = 0;
The getCheckedValue function will return the value attribute of my input if exists.
function getCheckedValue(radioObj) {
var radioLength = radioObj.length;
for(var z = 0; z < radioLength; z++) {
if(radioObj[z].checked) {
return radioObj[z].value;
}
}
return "Error!";
}
Here is the problem. The function works fine, except the isolated area. allQuestion is my object where I stored the questions, the possible answers and the right answer, correctAnswer(I don't included it here but works correctly). I put a conditional statement to increase y and code>score with one if the allQuestions[y].correctAnswer is qual with the value of the user_choice.
function changeQuestion() {
//PROBLEM
if(allQuestions[y].correctAnswer == user_answer){
score += 1;
y++;
} else{y++;}
//PROBLEM
i = (i < allQuestions.length) ? (i + 1) : 0;
if (i == allQuestions.length) {
i = 0;
return question_paragraph.replaceChild(document.createTextNode(allQuestions[0].question), question_paragraph.firstChild);
}
var newNode = document.createTextNode(allQuestions[i].question);
console.log(score);
return question_paragraph.replaceChild(newNode, question_paragraph.firstChild);
}
Finnaly, I called the addHandler function.
function addHandler(name, type, handler){
if (name.addEventListener){
name.addEventListener(type, handler, false);
} else if (name.attachEvent){
name.attachEvent("on" + type, handler);
} else {
name["on" + type] = handler;
}
}
addHandler(next_button, 'click', changeQuestion);
Well, something just appears to be funny here so far. First of all, I don't see any initialization to the variable y. If y is a global variable that is retaining its value, then maybe there is an issue with your object: allQuestions{}. Could you provide the code for building your object allQuestions{}? Without it, I don't think that I could fully answer this question, but I believe that is where your problem lies.
Oops, this was supposed to be a comment, not an answer, sorry...

Categories