wharfdale
wharfdale

Reputation: 752

Get javascript variable value from another function

I've declared a variable in the first .click function, but on my second .click I am trying to get the first variable value, but it's not been able to find it, due to it being in a different function.

How can I set a global variable or something where other functions can use the value too?

$('input[type="checkbox"]').click(function(){
    var checked = 0;
    if($(this).prop("checked") == true){
        var checked = 1
        console.log('checked');
        console.log(checked);
    }
    else if($(this).prop("checked") == false){
        var checked = 0
        console.log('not checked');
        console.log(checked);
    }
});
$('#button-cart').click(function(){
    if(checked == 1){
        alert('can continue fine');
    } else if(checked == 0){
        alert('cannot continue');
    }
})

Error: Uncaught ReferenceError: checked is not defined

Upvotes: 0

Views: 217

Answers (2)

dee-see
dee-see

Reputation: 24078

To avoid polluting global scope, the best practice would be to declare the checked variable within a closure so that only your event handlers can access it.

(function() {
    var checked; // No one outside of this immediately invoked function can see the checked variable.
    $('input[type="checkbox"]').click(function(){
        checked = 0;
        if($(this).prop("checked") == true){
            checked = 1
            console.log('checked');
            console.log(checked);
        }
        else if($(this).prop("checked") == false){
            checked = 0
            console.log('not checked');
            console.log(checked);
        }
    });
    $('#button-cart').click(function(){
        if(checked == 1){
            alert('can continue fine');
        } else if(checked == 0){
            alert('cannot continue');
        }
    })
}());

This way, both your click handlers can see the checked variable but it can't be accessed by anyone else.

Upvotes: 3

millerbr
millerbr

Reputation: 2961

Declare checked outside the functions - this makes it accessible on the global scope. Then remove the var statements inside the function, or you will create a new variable in the function scope. This code will work:

var checked = 0;
$('input[type="checkbox"]').click(function(){
    if($(this).prop("checked") == true){
        checked = 1
        console.log('checked');
        console.log(checked);
    }
    else if($(this).prop("checked") == false){
        checked = 0
        console.log('not checked');
        console.log(checked);
    }
});
$('#button-cart').click(function(){
    if(checked == 1){
        alert('can continue fine');
    } else if(checked == 0){
        alert('cannot continue');
    }
})

Upvotes: 2

Related Questions