Andrew
Andrew

Reputation: 55

Setting a global variable and accessing it in jquery/javascript

I'm having problems creating a global variable and resetting it through jquery. here is my code

var x = 1;
$(document).ready(function () {
    $("#button").click(function () {
        if(x === 1) {
            alert("test1");
            var x = 2;
        } else if(x === 2) {
            alert("test2");
            var x = 3;
        } else {
            alert("test 3");
        }
    });
});

I want to be able to click the same button three times and have all the tests appear, but instead it goes straight to the last option "test 3". I apologize if this is a silly question, but I'm a bit new to jquery and javascript.

Upvotes: 2

Views: 9609

Answers (1)

Coin_op
Coin_op

Reputation: 10728

Just remove the var from the variable assignment inside the click event callback. The var makes the variable local to that scope/closure.

 if (x === 1) {
      alert("test1");
      x = 2;
  }
  else if (x === 2) {
      alert("test2");
      x = 3;
  }
  else {
      alert("test 3");
  }

As a side point the very first var is not necessary, var x = 1 and x = 1 does the same thing when the code is not in a closure/function. All they are doing is assigning window.x = 1.

Upvotes: 3

Related Questions