How to increment a variable after button press - javascript

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).

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.

Javascript: Arrays and For Loop Basics

I'm new to javascript and have been trying to teach myself the basics. I do have some experience with C++.
I came across this example in the source I'm using for studying and the for loop looks strange to me:
<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
var allcookies = document.cookie;
alert("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
alert("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>
Would someone mind explaining why there is a [0] and [1] near the end of these statements?
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
A clearer way to write this statement is this:
var parts = cookiearray[i].split('='),
name = parts[0],
value = parts[1];
That doesn't have anything to do with the for-loop itself. Split returns an array of tokens; the string is split up at the given delimiter. You're simply accessing the first and second tokens in this array.
String.split creates an array using the assigned delimiter (in this case '='). The [0] and [1] are selecting the first and second elements of the array respectively (Javascript array element indexes start at zero).
Those are used to access the items in the arrays that you create.
It's more clear what they do, and also better for performance, if you put the array in a variable and access that. That way you don't have to create two identical arrays:
var cookie = cookiearray[i].split('=');
var name = cookie[0];
var value = cookie[1];
The code is splitting each cookie pair key=value into key ([0]) and value ([1]).
A for loop is an iterator. You can sort of think of it like a counter, or stepping progression. If you want to do something x number of times, then a for loop is your best friend. The issue, when you are first learning, is figuring out how to use them effectively.
I'll give you a relevant and nonrelevant (simplified) example:
Nonrelevant:
// Increase the value of x and print the new value to the console 20 times.
var x = 6;
for(var i = 0; i < 20; i++) {
x++;
console.log("Value of x: " + x);
}
If you take a close look it's really rather logical. You define an iteration variable i, tell it when to stop (i < 20...so stop if i = 20), how to progress with each iteration (i++ or i + 1).
So the code will enter the loop when i = 0...it will add 1 to the value of x (x++), resulting in x = 7. It does the same for each iteration, so when i = 1, x (7) + 1 = 8, so on and so forth until i = 20, then the code breaks out of the loop and continues on it's merry little way. When it breaks we have just added 1 to x 20 times. Since x used to equal 6, it now equals 26.
Relevant:
// Given array of length 10, print each element to the console
for (var i = 0; i < cookiearray.length; i++){
console.log(cookiearray[i]);
}
So here the for loop is the same, it simply iterates until i equals the length (number of elements, in this case) of the array (so 10 times). When i = 0, our code prints the element of the array at cookiearray[0]...when i = 1 it prints cookiearray[1]...so on and so forth for the entirety of the array.
What may confuse you in the example is the split function. Split returns an array. So this line:
name = cookiearray[i].split('=')[0];
...actually means assign the first element of the new array created from splitting the cookiearray's element at position i.
Let's assume that cookiearray[0] = "Hello=World". When i = 0, our code splits the string "Hello=World" into a new array where the element at the 0 position is "Hello", it then assigns this to the local variable name. So name = "Hello".

Trying to make a Javascript Array Print out using Inputted value

my first question would be am I correctly getting the value from id "textOne" into my var a? Second, I am supposed to have my while loop run "while the variable that represents the index value that I want to print" is greater than or equal to the minimum array value. Is my While loop condition correct?
I just basically want this to print out the correct number of indexes within my array based on the user input ranging from 1-5.
Thanks in advance.
<input type="button" value="Click" onclick="JobDuties()" />
to see my top
<input type="text" id="textOne" />
job duties here
<p id="answer"></p>
<script type="text/javascript">
function JobDuties()
{
var x = "";
var a = document.getElementById('textOne').value;
var b = a - 1;
myduties = new Array();
myduties[0] = "Saab";
myduties[1] = "Volvo";
myduties[2] = "BMW";
myduties[3] = "Toyota";
myduties[4] = "Ford";
}
while (a>=0)
{
x = x + myduties[b];
document.getElementById("answer").innerHTML=x;
}
</script>
I will assume you want to print out the correct array value, not arrays, as there are not multiple. PS> People do not like homework questions on here if you do not say so because answering completely does not help you learn. I will partially answer.
You do not need to loop through the array to look up a value.
You can initialize the array more easily.
["Saab", "Volvo", ... ]
You can reference a position in the array, like so for Saab as it is zero indexed
myduties[0]
If you are going to loop, which I am still not seeing why you would do that.
Code below:
var i = 1; //The variable you increment up to the use input variable a
while(i =< myduties.length){
if(i == a){ //if i and a are same then that position
//in the array will have the car type the user requested
myduties[i-1] //and set it to the DOM or document element similar to what you already had
}
i = i + 1; //Increment i towards the one less than the length of the array
}
Not perfect or checked but that should provide you with some pointers.

"Score" variable not changing

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; }

Categories