0

I've written a piece of javascript/jquery that reads a textfile.
I'm having trouble with the variable "fieldname". I declared it in the outer function(), and I assign a value to it in the inner function() that actually reads the file. But right after I leave the inner function, the content of the variable is lost. The code:

<script>
    $(document).ready(function(){

        var usedlanguage = $("#usedlanguage").html();
        var fieldname = new Array();

        $.get('Language.txt', function(data)
        {
            var lines = data.split('\n');

            var res="";

            for(var i = 0; i<lines.length;i++)
            {
                var splitup = lines[i].split('\t');

                fieldname[i] = splitup[0];
                res = res + fieldname[i] + '\n';
            }

            alert("fieldname length = " + fieldname.length); // here everything is OK
            alert("" + res);                                //this is good.

        });

        alert("fieldname length = " + fieldname.length);    // here it suddenly returns 0.

 }); 
</script>     

Is there something wrong with my understanding of scopes? Or is it a problem that there are two function() defined? Or something else?

blubbiedevis
  • 415
  • 3
  • 11

1 Answers1

0

You need to declare the variable outside DOM ready event to make it global. currently its context remains only in ready event and not beyond that. Use it in this way::

var fieldname = new Array();
$(document).ready(function(){
  //rest code
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125