1

I have 2 js files: 1.js and 2.js.
In 1.js I have a variable

var test ='Hello';

I'm trying to access the variable in 2.js

alert(test);

Sample Code:
1.js :

$(document).ready(function () {
    var test = 'Hello';
});

2.js :

 $(function () {
       function getData(){
            alert(test);
       }
   }); 

In my aspx page order of js files:

<script type="text/javascript" src="js/1.js"></script>      
<script type="text/javascript" src="js/2.js?"></script> 

I know the question is asked before many times but none of the answers seems to work for me.

James Z
  • 12,209
  • 10
  • 24
  • 44
CrazyCoder
  • 2,194
  • 10
  • 44
  • 91
  • JS doesn’t work like that. `test` is scoped to the function it’s defined in, here the anonymous function passed in to jQuery’s DOMReady shortcut. – Dave Newton Dec 08 '17 at 04:17

2 Answers2

1

Make sure your var test is not inside a function and that your file is load in the correct order. In your first file use something like

<script type="text/javascript">
  var test = "myVar"
</script>
// Now here include your js file too JS file 
// Or set in window scope like window.test="myVar";

And in your JS file use like

$(function() {
  alert(test);
  // alert(window.test);
});

A variable in global scope can be access from all javascript file. Your first js file

Here is another way.

//first.js file don't put variable inside any function here.
var globalVariable={
   test: 'myVar'
};

And your second js file

//second.js file
alert(globalVariable.test);

And in html page add

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

More from here

Bhuwan
  • 16,525
  • 5
  • 34
  • 57
manikant gautam
  • 3,521
  • 1
  • 17
  • 27
0

You can use sessionStorage to store the variable value

$(document).ready(function () {
  sessionStorage.setItem('test ', 'Hello');
});

In the next file retrieve it using

$(function () {
       function getData(){
         var data = sessionStorage.getItem('test');
            alert(data );
       }
   });

Note the file 1.js need to be loaded before 2.js

brk
  • 48,835
  • 10
  • 56
  • 78
  • Important to note storage only stores strings....booleans and numbers need to be type cast on retrieval and arrays/objects need to be stringified and parsed – charlietfl Dec 08 '17 at 04:36