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?
Brian Tompsett - 汤莱恩
5,92772 gold badges64 silver badges135 bronze badges
asked Aug 29, 2012 at 18:32
lomse
4,1668 gold badges51 silver badges68 bronze badges
1 Answer 1
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);
}
answered Aug 29, 2012 at 18:33
Michael Berkowski
271k47 gold badges452 silver badges395 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
lomse
How could've I missed this? This makes sense. Thanks a lot.
lang-js
my_valueeach time themanagefunction is called. It seems you want a global variable.