Search code examples
javascriptdom-eventsglobal-variables

How to pass a global variable to multiple functions in multiple files


<script> 
var word = new Array(); word[1] = 'new'; word[2] = 'old';
</script> 

<script src="javascript/validator.js" type="text/javascript"></script>

And, in the validator.js we have:

function validate(number){ 
  alert(word[number]);
}

How to catch the variable value? I always get an error saying the variable doesn't exist.


Solution

  • You almost got it.

    This is the way I managed my multi-language message:

    First I defined the array at the top of the page; as close as possible to the HEAD tag

    <script type="text/javascript">
        var resx = {};
    </script>
    

    Then, I fill the array with the values, using whatever method you use to get it from the database. In this example I use ASP.NET MVC.

    <script type="text/javascript"> 
         resx["word1"] = '@Model.word1';    
         resx["word2"] = '@Model.word2';    
         //or you can fill it directly
         resx["word3"] = 'Name';
         resx["word4"] = 'Nombre';
    </script>
    <script src="javascript/validator.js" type="text/javascript"></script>
    

    Then you use the way you want in the js file:

    validate(“word2”);
    function validate(value){ 
       alert(resx[value]);
    }
    
    //Or:
    alert(resx[“word3”]);
    

    I hope this help.