2

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
1
  • You are re-declaring my_value each time the manage function is called. It seems you want a global variable. Commented Aug 29, 2012 at 18:34

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

How could've I missed this? This makes sense. Thanks a lot.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.