Variable doesn't work as it should - javascript

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 .

Related

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

Can I use a string variable in document.getElementById()?

here is my code:
function figureSelector () {
document.getElementById("rook").onclick = function () {
curr = '"rook"';
};
};
function moveLine(){
document.getElementById("upButton").onclick = function() {
document.getElementById(curr).style.top = document.getElementById(curr).offsetTop - getPix() * 62 + "px";
counter= counter + getPix();
};
I want to write an universal function for a chess piece to move. All I want is, when one clicks the chess piece, and then presses the up button, it must go up.
Yes you can use String variable:
HTML:
<div id="name" style="width:300px;height:300px;background:red"></div>
javascript:
var b = 'name';
document.getElementById(b).innerHTML = 'none';
jsfiddle here
Yes, you can.
Just use
curr = 'rook';
(without the extra quotes)
You can even do stuff like this:
function mark(yy) {
for (var ii = 0; ii < 7; ii++ ) {
if ( ii == yy ) {
document.getElementById("b"+ii).style.fontWeight = "bold";
}
...
But be careful of your loop limits to be sure you have a matching id. I just spent hours trying to figure out why ("b"+ii) was getting error and finally realized that the error was being caused by exactly that. duh...
Yes, Mate, you can.
You can use a variable as the argument for any function. That's just how functions work -- they don't care where the argument comes from. You should define curr outside those functions.

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

cannot get a variable to pass from function called onclick

I am calling a function onclick secVar(sec1); which should run it through the script below, but it does not seem to be doing so, can someone tell me what I am doing incorrectly. I am new to javascript, and only have a little experience into scripting, and this code seems to be doing less and less of what I want it to.
<script type="text/javascript">
var sec1=0;
var sec2=0;
var sec3=0;
function secVar(){
if(sec1) {
sec1++;
document.getElementById('sec1text').innerHTML = sec1;
}
if(sec2) {
sec2++;
document.getElementById('sec2text').innerHTML = sec2;
}
if(sec3) {
sec3++;
document.getElementById('sec3text').innerHTML = sec3;
}
}
function largestVar(){
if (sec1 >= sec2 && sec1 >= sec3) {
//a
document.getElementById('rig').innerHTML = 'Test1';
} else if (sec2 >= sec1 && sec2 >= sec3) {
//b
document.getElementById('rig').innerHTML = 'Test2';
} else {
//c
document.getElementById('rig').innerHTML = 'Test3';
}
}
</script>
If this helps, The old code was the code below, before I tried to add in the script to determine the largest of the variables. It was incrementing the variables onclick, but no longer so. The onclick contained sec1Var() at that point.
<script type="text/javascript">
var sec1=0;
var sec2=0;
var sec3=0;
function sec1Var(){
sec1++;
document.getElementById('sec1text').innerHTML = sec1;
}
function sec2Var(){
sec2++;
document.getElementById('sec2text').innerHTML = sec2;
}
function sec3Var(){
sec3++;
document.getElementById('sec3text').innerHTML = sec3;
}</script>
If someone can explain to me what I am doing wrong I would greatly appreciate it.
I think it's hard to tell what your intention is. Sparticus has it right IF what you're trying to do is see if sec1, 2, and 3 are currently true or false (0 or 1). Since they are currently false, the code will never do anything as Sparticus correctly points out.
However, I'm not convinced that's actually what you MEAN to do. It looks like the condition you want to check is whether or not you're trying to increment sec1, 2, or 3. In other words, "If you are passing me sec1, increment it and update a piece of HTML".
But variables don't work that way. When you say secVar(sec1) what you are actually saying is `secVar(0)'. I don't think that's your intention.
So, a big waste of my time if I'm wrong, but because I'm already rolling along, let's pretend I'm right:
secVar needs to be able to accept a parameter, but right now you've declared it void. Changing it to accept a parameter is a first step:
function secVar(param) { ... };
But this still won't do anything. Because when you're still passing it "0" with your existing syntax. You need to pass it something that can be checked, like a string:
secVar('sec1');
When you do this, you can now update your conditions to check which string is being passed
if (param === 'sec1') { ... }
Here's a fiddle: http://jsfiddle.net/ch4yk/
Notes:
The fiddle includes jQuery just for easy brute-force event binding on the buttons. It's just an example. You don't need jQuery; bind your events however you want.
It is currently not doing anything with the largest value function, even though the code is in the fiddle
None of your counters will increment in this implementation.
When secVar() gets run, all the counters are at zero. They never increment because they start at zero.

basic jquery looping question around 'click'

Basic question, but I have been pounding my head for a bit so thought id bring it here.
html looks like this (edit, fixed the closing quotes)
<span class='deleteimage-119'>delete</span>
<span class='deleteimage-120'>delete</span>
<span class='deleteimage-121'>delete</span>
<span class='deleteimage-122'>delete</span>
<span class='deleteimage-123'>delete</span>
javascript/jquery looks like this
iids = ['119','120','121','122','123'];
for (i=0; i<iids.length; i++) {
place = iids[i];
$(".deleteimage-" + place).click(function () {
alert(place);
});
}
The click functionality gets attached to each individual span, but the alert after clicking just shows the last item in the array.
You have a scoping issue. By the time the callback fires, place has the last value from the loop.
You need to create a new variable for the closure; one variable per iteration, each of which will then be "caught" by the closure and used in the callback.
It would be nice if the solution were this:
var iids = ['119','120','121','122','123']; // don't forget `var` please
for (var i=0; i<iids.length; i++) {
var place = iids[i]; // local variable?
$(".deleteimage-" + place).click(function () {
alert(place);
});
}
Alas, Javascript has no block scope so there's still only one variable here called place, and it keeps getting updated as the loop runs.
So, you have to use a function instead:
var iids = ['119','120','121','122','123'];
function f(place) {
// NOW `place` is a local variable.
$(".deleteimage-" + place).click(function () {
alert(place);
});
}
for (var i=0; i<iids.length; i++) {
f(iids[i]);
}
There are neater ways to employ this function approach using closures and bound variables, and the other answers cover those neater ways quite well. My answer has focused on explaining the issue.
The issue is with scopes and closure.
In JS the scope is # function level and not block level.
Try this:
var iids = ['119','120','121','122','123'];
for (i=0; i<iids.length; i++) {
place = iids[i];
var clickFn = function(a){
return function(){
alert(a);
}
}(place);
$(".deleteimage-" + place).click(clickFn );
}
This is because the click is occurring after the loop is completed, so you're alerting place = iids[iids.length - 1]. In order to achieve the result you're looking for you need to create a function closure and pass place in as a parameter:
iids = ['119', '120', '121', '122', '123'];
for (i = 0; i < iids.length; i++) {
place = iids[i];
(function(_place) {
$(".deleteimage-" + _place).click(function() {
alert(_place);
});
} (place));
}
Inside the loop, you are binding the click event to those span, but the events are fired only after the loop is complete. So, it will always show the last value.
As others have mentioned, you have a scoping issue. Unless all of those classes have a unique meaning, I'd move the place value to a data attribute and leave deleteimage as the class name. Something like:
<span class='deleteimage' data-place='119'>delete</span>
<span class='deleteimage' data-place='120'>delete</span>
<span class='deleteimage' data-place='121'>delete</span>
<span class='deleteimage' data-place='122'>delete</span>
<span class='deleteimage' data-place='123'>delete</span>
$(".deleteimage").click(function() {
var place = $(this).data("place");
alert(place);
});
If the place values aren't unique values, then this answer doesn't apply.

Categories