Sri Harsha
Sri Harsha

Reputation: 107

Updating the value of a variable

How to update the value of a variable in javascript? I have tried it using the code below,but it isn't working. I have took a button and a p tags with id's a,b,c. If x=0,John gets a point. If x=1,Rob gets a point. If x=2,Lee gets a point. Initially,when I run the code,i,j,k are being display Then,x updates,but i,j,k are not getting updated. That is if john gets a point for second time i is not being updated to 2. Please help me to solve this problem. See the code below.

    document.getElementById("but").onclick=function(){
        var x=Math.random();
        x=3*x;
        x=Math.floor(x);
        var i=0,j=0,k=0;
        if(x==0){
            ++i;
            document.getElementById("a").innerHTML="John:" +" "+i;
        }else if(x==1){
            ++j;
            document.getElementById("b").innerHTML="Rob:" +" "+j;
        }else if(x==2){
            ++k;
            document.getElementById("c").innerHTML="Lee:" +" "+k;
        }
    }

Upvotes: 1

Views: 61

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

That is if john gets a point for second time i is not being updated to 2

You're not doing anything anywhere in your code that knows about what's gone before. You're overwriting the content of the elements by assigning to innerHTML each time.

If you want to keep track of previous values, you'll either have to grab the value from the input before updating it (clunky), or track them separately, for instance in an object that's held outside the function:

// An object to keep values in
var scores = {
  a: 0,
  b: 0,
  c: 0
};
document.getElementById("but").onclick = function() {
  var x = Math.random();
  x = 3 * x;
  x = Math.floor(x);
  if (x == 0) {
    ++scores.a;
    document.getElementById("a").innerHTML = "John:" + " " + scores.a;
  } else if (x == 1) {
    ++scores.b;
    document.getElementById("b").innerHTML = "Rob:" + " " + scores.b;
  } else if (x == 2) {
    ++scores.c;
    document.getElementById("c").innerHTML = "Lee:" + " " + scores.c;
  }
}
//
<input type="button" id="but" value="Click me">
<div id="a">(blank)</div>
<div id="b">(blank)</div>
<div id="c">(blank)</div>

We can refactor that further to reduce the duplicated code, and to initialize the elements up front when the values are 0:

// An object to keep values in
var scores = [
  {name: "John", score: 0, id: "a"},
  {name: "Rob", score: 0, id: "b"},
  {name: "Lee", score: 0, id: "c"}
];
scores.forEach(showScore);
document.getElementById("but").onclick = function() {
  var entry = scores[Math.floor(Math.random() * 3)];
  ++entry.score;
  showScore(entry);
}
function showScore(entry) {
  document.getElementById(entry.id).innerHTML =
    entry.name + ":" + " " + entry.score;
}
<input type="button" id="but" value="Click me">
<div id="a">(blank)</div>
<div id="b">(blank)</div>
<div id="c">(blank)</div>

Upvotes: 1

Related Questions