DolDurma
DolDurma

Reputation: 17301

global function in jquery

i cant access to variable of ok in this code. how to set this variable for global access

$('#Btn1').click(function(){
var ok=true;
});
$('#Btn2').click(function(){
 if ( ok ) alert('ok');
})

Upvotes: 0

Views: 300

Answers (5)

palaѕн
palaѕн

Reputation: 73906

Try this:

// this is a global variable
var isValidGlobal = false;

$(function() {
    // since this is global, i can alert it here
    alert(isValidGlobal);

    $('#Btn1').click(function() {
        // Set the global variable
        isValidGlobal = true;
        return false;
    });

    $('#Btn2').click(function() {

        if (isValidGlobal) alert('global variable');
        return false;
    });
});​

DEMO

Upvotes: 0

Shadow Wizard
Shadow Wizard

Reputation: 66388

While using a global variable will work fine, if your goal is just to know whether the first button was clicked or not, better (and more jQuery-ish) approach would be to store that data as part of the button itself, using the jQuery .data() method.

To make it even more flexible you can even save the number of times the button was clicked, then check that value when clicking the other button:

$('#Btn1').click(function(){
    $(this).data("click_count", (parseInt($(this).data("click_count")) || 0) + 1);
});

$('#Btn2').click(function(){
    var clickCount = (parseInt($('#Btn1').data("click_count")) || 0);
    if (clickCount > 0) {
        alert("clicked at least once");
    }
})​

Live test case.

Upvotes: 0

drewinglis
drewinglis

Reputation: 434

To create global functions in JavaScript, you omit the var:

ok = true;

However, better style would be to declare the variable somewhere that is in scope for both functions, but in its own namespace, to avoid namespace pollution:

function () {
    var ok = false;
    $('#Btn1').click(function(){
        ok=true;
    });
    $('#Btn2').click(function(){
        if ( ok ) alert('ok');
    });
}

(Edit: formatting)

Upvotes: 0

YogeshWaran
YogeshWaran

Reputation: 2281

just declare ok variable outside your handler

var ok=false;
$('#Btn1').click(function(){
  ok =true;
});
$('#Btn2').click(function(){
 if ( ok ) alert('ok');
})

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318518

Remove the var and declare the variable in the outer scope instead:

var ok = false;
$('#Btn1').click(function() {
    ok = true;
});
$('#Btn2').click(function() {
    if(ok) alert('ok');
});

While removing var would be enough to make the variable global, it's much better to keep it local to the smallest possible scope - in this case that's the scope containing those two functions. Since you probably wrapped that code in a document ready callback function it will be that function's scope instead of the global scope.

Upvotes: 2

Related Questions