Pixcaro
Pixcaro

Reputation: 1

How to update variable value using click and switch

$(document).ready(function() {

    var varChange = '';
    var baseVar = 50;

    selectBaseVar = function(){
        switch (varChange) {case 101: varChange = 501; break;
                            case 501: varChange = 101; break;
                            default:  varChange = 101; break;}
        console.log('internal val: '+varChange);
        return varChange;
    };

    $("#myButton").click(function(){
        selectBaseVar();
    });

    selectBaseVar();

    console.log('external val: '+varChange);
    console.log('base baseVar = '+baseVar);
    baseVar += varChange;    // How do I update this value upon the button click event?
    console.log('updated baseVar = '+baseVar); // it works only in the document.ready state
});

Works for the document.ready state but not for the click event. A scope problem is maybe the cause.

I don't know how to workaround this issue


The intention is to left baseVar as constant @ 50
Increase the value of baseVar, due
baseVar += varChange;
Switch varChange, and update baseVar


In docuent.ready state we got:


internal val: 101
external val: 101
base baseVar = 50
updated baseVar = 151


if I click, respectively I got internal values as expected:
internal val: 501
internal val: 101


But (updated baseVar = 151) no matter what value it’s switching


And not what I’m up to, that is affecting the external variable baseVar with the values of:
updated baseVar = 151
updated baseVar = 551


note: there is a good reason to leave the baseVar variable out of the scope of the selectBaseVar() for the sake of other functions that benefit from the switch result of the same, but been out of the scope of selectBaseVar().


Thanks

Upvotes: 0

Views: 113

Answers (2)

vzwick
vzwick

Reputation: 11044

It seems what you're trying to achieve is this:

$(document).ready(function() {

    var varChange, baseVar = 50;

    selectBaseVar = function(){
        varChange = (varChange == 101) ? 501 : 101;
        console.log('internal val: '+varChange);
        return varChange;
    };


    $("#myButton").click(function(){
        selectBaseVar();
        baseVar += varChange;
        console.log('button handler val: ' + varChange);
    });

    selectBaseVar();

    console.log('external val: ' + varChange);
    console.log('base baseVar = ' + baseVar);
    baseVar += varChange;    // How do I update this value upon the button click event?
    console.log('updated baseVar = ' + baseVar); // it works only in the document.ready state    
});

Upvotes: 1

Alex Peattie
Alex Peattie

Reputation: 27647

It seems to work for me:

http://jsfiddle.net/mkqmm/1/

Make sure you're wrapping the code in

$(document).ready(function() {

});

Upvotes: 1

Related Questions