4

I have this code in jQuery..

$(document).ready(function(){ 

var fieldCounter = 0;  ...

I have a jQuery function that increments this value.

This works, but I can't access this value on the page from a non-jQuery function? The reverse is also true, if I scope it in JavaScript e.g.

<script type="text/javascript">

var fieldCounter = 0;

I can access it from javascript but jQuery can't view it?

I'm probably doing something really dumb?

Shog9
  • 156,901
  • 35
  • 231
  • 235
Brett
  • 2,537
  • 4
  • 19
  • 16

6 Answers6

8

It has nothing to do with jQuery, but all with Javascript scope.

$(document).ready(function() { 
   var fieldCounter = 0;
});

fieldCounter is declared inside a function. Since Javascript has function scope, the variable is not visible outside the function.

BTW, jQuery is Javascript, they play by the same rules, they're not two different technologies.

Exhaustive answers can be found here: What is the scope of variables in JavaScript?

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
  • +1 The question you linked to has some pretty detailed answers. – Roman Apr 08 '10 at 04:15
  • Thanks all, turns out as I thought, the problem was an ajax load I was doing had the same variable in it causing it to reset.. I'll award this one the answer as it was the first correct. Thanks all again.. – Brett Apr 08 '10 at 04:43
2

jQuery is not magic. It is a JavaScript library. Your issue is that you're defining a local variable inside a function. Due to the way JavaScript lexical scoping works, you can't access it outside that function (with the exception of closures, which does not apply here).

Most likely, you just want:

$(document).ready(function(){ 

fieldCounter = 0;

That will make it a global variable.

Edit: Note that using a namespace and/or declaring the global variable is cleaner, but not required.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • 2
    What? Only if he's declared the variable previously with a `var` statement. Otherwise it's an unknown indicator and doesn't interpret. – Christian Mann Apr 08 '10 at 04:18
  • 2
    Christian, you have strange terminology. With lexical scoping, assignment against a variable looks up the scope chain for a matching variable, and if not found, creates it at the highest possible scope, in this case the window object. – Luke Schafer Apr 08 '10 at 04:21
  • 1
    @Christian: That's probably not true. As far as I know an assignment without the *var* keyword creates a global variable. – Georg Schölly Apr 08 '10 at 04:22
  • @Christian I'm not sure what the spec says, but he's right. That's the way it works in current browser implementations. `fieldCounter` will be attached to the global object in this case. – deceze Apr 08 '10 at 04:22
  • It's valid syntax. Without a `var`, the global scope is assumed. – harto Apr 08 '10 at 04:23
  • Huh. You learn something new every day. I should learn to research before I post... – Christian Mann Apr 08 '10 at 04:30
  • 3
    The ECMAScript spec addresses this fully. In summary, assigning to a variable that is not declared anywhere on the scope chain is not quite the same as declaring a global variable, but for most purposes it comes to the same thing. The difference is that using `var` prevents you from deleting the variable using the `delete` operator whereas assigning to an undeclared variable does not. I recommend kangax's article on this: http://perfectionkills.com/understanding-delete/#undeclared_assignments – Tim Down Apr 08 '10 at 08:23
1

Your problem in the first case is scope. By putting the var init inside a function declaration, you've scoped it to access inside that function.

Something else is going on in the second case; more code would be necessary to see what.

The global scope in Javascript is window. That means that when you declare variables directly in <script> tags, you can get them back by asking for window.variableName.

A common way to resolve these kinds of scoping issues is to create a namespace framework. If you do it right you can call myNamespace.subNamespace.variable and have full confidence that because it's explicitly scoped to window, you can get it back no matter where you are.

Remember that jQuery is built in Javascript. There's nothing special about it.

issa marie tseng
  • 3,194
  • 22
  • 20
0

JavaScript has function scope.

var count = 8;

var myfunction = function() {

   var newCount = count + 1;

};

alert(newCount); // undefined
alex
  • 479,566
  • 201
  • 878
  • 984
0

it's because of the scope of javascript... try to read this

Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
0

Variables declared inside jQuery code block will have local scope.If you need to access a variable both in local javascript function as well as jQuery code block then declare the variable at global level. Sample Code snippet :-

 <script type="text/javascript" language="javascript">
        var increment = 0;
        $(document).ready(function() {
            $("#button2").click(function() {
                increment = increment + 1;
                alert(increment);
            });
        });
        function ClickMe() {
            increment = increment + 1;
            alert(increment);
        }
    </script>
Pawan Mishra
  • 7,212
  • 5
  • 29
  • 39
  • I did this but it still doesn't work? I've put var fieldCounter = 0; in the javascript, and incrementing in the jquery function doesn't update it? – Brett Apr 08 '10 at 04:34
  • In that case please provide the code snippet which you have written.The qustion has been answered in perfect way and it has also been marked as answered.If you can provide the code which you have written , then probably someone amongs us can help you. – Pawan Mishra Apr 08 '10 at 04:50