74H1R
74H1R

Reputation: 3514

How to get global variable in JQuery functions

I want to access my global javascript variable in JQuery methods. But I am unable to get it when I go to attach a click even to a div. As following.

How can I do that? I mean do I need to rely on hidden fields for some state management?

var divCount = 3;
$(function() {
//divCount is accessible here
    $("#sortable").sortable({
        revert: true
    }); 

    $("#new").click(function(){
        if (divCount<7){
                     //divCount is not accessible here. why? and how?
            var thisCount =  ++divCount;    

            $("#draggable_"+thisCount).addClass("draggable");
        }
    });
});

Upvotes: 1

Views: 3296

Answers (2)

Prutswonder
Prutswonder

Reputation: 10064

I tried this sample and it worked for me:

var divCount = 3;
$(function() {
    $("#new").click(function(){
        divCount++;
        alert(divCount);
    });
});

So the scope of divCount is not the problem here, but something else is. I suggest you try to pinpoint the cause by commenting out the other jQuery statements until it works, and then remove the comments until the error occurs. Maybe there's a jQuery library file missing (I noticed the jquery-ui tag in your question).

Upvotes: 2

Fitzchak Yitzchaki
Fitzchak Yitzchaki

Reputation: 9163

This is not make any sense. It is need to be accessible.

Upvotes: 0

Related Questions