1

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>");
    });

2 Answers 2

3

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.]

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

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.