www.webdeveloper.com
Results 1 to 4 of 4

Thread: [RESOLVED] Issue with variable scope in Javascript

Hybrid View

  1. #1
    Join Date
    Aug 2012
    Posts
    3

    resolved [RESOLVED] Issue with variable scope in Javascript

    Hey guys,

    I'm new to javascript and jQuery, so be gentle

    The issue is when I hook actions to id's

    Code:
            for(var i = 0; i < categoryNames.length;i++)
                    {
                        var category = Sanitize(categoryNames[i]);
       
                        for(var j=0; j < categoryExpenses[i].length;j++)
                        {
                            var expense = Sanitize(categoryExpenses[i][j]);
                            
                            $('#' + category + "_" + expense+"_type").change(function() {
                                alert("changed")
                            });
                            
                            $('#' + category + "_" + expense+"_amount").keyup(function() {
                                var tmpi = i;
                                alert(i+","+tmpi)
                            });
                        }
                    }
    Essentially what I am trying to do is pragmatically hook listeners to a ton of option selection boxes and input fields.

    Since the "keyup" and "change" hooks are only called when they happen, I understand why "i" and "j" will always be "categoryNames.length+1" and "categoryExpenses[i].length+1" respectively. (because the iteration will have already happened and they would have already dropped out of the for loops, thus later when an action happens it will be what is last was) what I do not understand is why "tmpi" is always equal to "categoryNames.length+1".

    I assumed (obviously incorrectly) that a variable declared within the scope of the internal hook function would only take on the value passed to it at inception. I appears as if the function doesn't actually get instantiated until it is called by a "keyup" or a "change". If this is the case I don't know how to generate lots of these hooks without doing them one at a time that would be a ludicrous. (my project will involve hundreds of these tedious things) Another option is to write a script to generate all code and then just copy paste it. Either way I really don't like how messy and inefficient that is.

    I guess my question is, "How do I pragmatically do this for 60-70 different objects without making my code nightmarish?"

  2. #2
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,648
    eval() will save your soul

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>Voodoo magic</title>
    <style>
    body{text-align:center;padding-top:200px;}
    #res span{color:Crimson;font-weight:bold;}
    </style>
    <script>
    window.onload=function(){
    var sel=document.getElementById('sel'),res=document.getElementById('res');
    for(var i=1;i<71;i++){
    eval('sel.options[sel.options.length]=new Option('+i+','+i+');');
    }
    sel.onchange=function(){
    res.innerHTML='<br /><br />selectedIndex = <span>'+this.selectedIndex+'</span><br />value = <span>'+this.options[this.selectedIndex].value+'</span>';
    this.blur();
    }
    }
    </script>
    </head>
    <body>
    <select id="sel"></select>
    <div id="res"></div>
    </body>
    </html>
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  3. #3
    Join Date
    Aug 2012
    Posts
    3
    Padonak,

    Although the Voodoo Magic of your code did confuse me, I think I used the basic principle in a different way. What I did was store "data-i" and "data-j" inside each individual DOM, and recall them from the DOM when an event fired. The solution looks as follows:

    Code:
    for(var i = 0; i < categoryNames.length;i++)
                    {
                        var category = Sanitize(categoryNames[i]);
                        
                        for(var j=0; j < categoryExpenses[i].length;j++)
                        {
                            var expense = Sanitize(categoryExpenses[i][j]);
                            $('#' + category + "_" + expense+"_amount").data("i",i).data("j",j);
                            $('#' + category + "_" + expense+"_type").data("i",i).data("j",j);
                            
                            $('#' + category + "_" + expense+"_type").change(function() {
                                var tmpi = $(this).data("i");
                                var tmpj = $(this).data("j");
                                categoryAmounts[tmpi][tmpj] =$('#' + Sanitize(categoryNames[tmpi]) + "_" + Sanitize(categoryExpenses[tmpi][tmpj])+"_amount").val();
                                categoryTypes[tmpi][tmpj] = $(this).val();
                                
                                $('#' + Sanitize(categoryNames[tmpi]) + "_" + Sanitize(categoryExpenses[tmpi][tmpj])+"_amount").trigger({
                                        type: 'keyup',
                                        which: 13
                                });
    
                            });
    
                            
                            $('#' + category + "_" + expense+"_amount").keyup(function() {
                                var tmpi = $(this).data("i");
                                var tmpj = $(this).data("j");
                                categoryAmounts[tmpi][tmpj] = $(this).val();
                                UpdateValue(tmpi,tmpj);
                            });
      
                        }
                    }
    Thanks for the nudge in the right direction.

  4. #4
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,648
    The data-* attributes are new in HTML5 (w3schools) what if we talked some time ago? ))
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles