tags:

views:

26

answers:

2

In this example:

I would like to use the "id" which is defined in the second function in the last (second) function. I thought using the "var" term would suffice but it doesn't.

Does anyone know how i could do it?

jQuery("td.setting").live("click",function(){
   text = jQuery(this).text();
   var id = jQuery(this).attr("id");

   jQuery(this).replaceWith("<td class=\"update\"><input class='inputSetting' type='text' value="+text+">  <img class=\"accept\" alt=\"accept button\" src='images/accept.png'></td>");
   console.log(id);
 });
 jQuery("img.accept").live("click",function(){

   jQuery("td.update").replaceWith("<td class=\"setting\"><proc name='C_Settings::getSavedSetting' params='"+id+"'></proc></td>");
    });
+1  A: 

If you use var, the variable becomes local to that function. You may want to define 'id' outside of both functions and it will be available to both the functions due to closures.

var id = null;
jQuery("td.setting").live("click",function(){
                        text = jQuery(this).text();
                        id = jQuery(this).attr("id");

                        jQuery(this).replaceWith("<td class=\"update\"><input class='inputSetting' type='text' value="+text+">  <img class=\"accept\" alt=\"accept button\" src='images/accept.png'></td>");
                        console.log(id);
        });
        jQuery("img.accept").live("click",function(){

                        jQuery("td.update").replaceWith("<td class=\"setting\"><proc name='C_Settings::getSavedSetting' params='"+id+"'></proc></td>");
    });

If you show us your HTML and tell us what you are trying to do, we can probably find a way to avoid using id like this. [Hint: Look at the data method available in jQuery.]

SolutionYogi
A: 

The problem is id doesn't exist in the current scope of the second function; it's only been defined in the first.

The only way to do it is to either define id at a higher scope, outside of the first function declaration, or just define it again within the scope of the second function.

Peter