lomse
lomse

Reputation: 4165

Change JavaScript function on the fly

Well this is supposed to be a simple one but have been giving me headache for two days now. I have the following:

<a href="javascript:void();" onclick="return manage(id, value)">Add or remove</a>

The manage function is as follows:

function manage(id, param){
    var my_value; 
alert(my_value); // this keeps giving me undefined. I want it to hold the last value of the param
    
    if(param!=0){ // value not empty, we are removing       
        my_value = remValue(id, param);
    }   
    else if(param==''){ // value is empty, so we are adding 
        my_value = addValue(id, param);
    }   
    alert(my_value);    
}

function addValue(id, param){
    param += 1; 
    return param;
    
}

function remValue(id, param){
    param -= 1; 
    return param;
    
}   

The whole idea is to assign the value of param to my_value after the adding or removing operation. Any help please?

Upvotes: 2

Views: 719

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270607

By defining var my_value; inside the function, you are redeclaring the variable to an undefined value on each function call. It is local only to that call and won't persist.

If you need it to retain the value, you simply need to declare it with var at a higher scope:

// Declare outside the function...
var my_value;
function manage(id, param){
    alert(my_value); // Should be undefined on first call, 
                     // or hold previous value on subsequent calls after assignment

    if(param!=0){ // value not empty, we are removing       
        my_value = remValue(id, param);
    }   
    else if(param==''){ // value is empty, so we are adding 
        my_value = addValue(id, param);
    }   
    alert(my_value);    
}

Upvotes: 4

Related Questions