javascriptjqueryvariables

jquery variable in function


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)


Solution

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