jquery variable in function

Go To StackoverFlow.com

6

On pageload I set a variable

$(document).ready(function() {
  var inv_count = 3;
  });

When I try to refer to that variable inside functions though, it doesn't work.

function blah(a,b) {
   alert (inv_count);
   }

Why is this? And how can I get around it?

(rookie here)

2012-04-05 17:12
by user1022585
make inv_count a global variable; it is inside a function. write it outside the ready functio - mshsayem 2012-04-05 17:15


11

If you declare a variable inside a function, the variable name will be inaccessible outside the scope of that function. Move the declaration outside the function:

var inv_count;
$(document).ready(function() {
    inv_count = 3;
});
2012-04-05 17:15
by Michael Liu
because its not a globally accessible variable - Kyle Yeo 2012-04-05 17:18


12

You have a problem of scope, I suggest you read a little about it because you can improve your javascript a ton, but you could solve it in two general ways:

var inv_count; //you declare your variable in a global scope, it's not very good practice
$(document).ready(function() {
    inv_count = 3;
});
function blah(a,b) {
   alert (inv_count);
}

or

$(document).ready(function() {
    var inv_count = 3;

    function blah(a,b) {
      alert (inv_count);
    }
    //you declare everything inside the scope of jQuery, if you want to acess blah outside use:
   //window.blah = blah;
});

Also I recommend you read about clousures if you don't know how they work.

2012-04-05 17:19
by nicosantangelo
very good cat!! - MCSI 2012-07-24 14:01
Ads