0

I have this javascript/jquery function in which I store each elements inside a div to an array. The problem is that it doesn't save the results outside of the anonymous function. How do you setup a global variable?

This is my Javascript/jquery

function store_options(){
    var stored_options = new Array;
    $('[id^="tagboxfv-"]').each(function(){
        var last_index = slice_last_index(this);
        $('[id="form-'+last_index+'"] > select[id="v-'+last_index+'"] > option').each(function(){
            stored_options[last_index] = [];
            stored_options[last_index][$(this).val()]=$(this);
        });
    });
}
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
taptipblard
  • 491
  • 1
  • 7
  • 15
  • possible duplicate of [What is the scope of variables in JavaScript?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Brian Dillingham Sep 07 '14 at 06:50

2 Answers2

2

In general using global variables in JavaScript is not recommended. Bu if you still want to use it just define it out of the function scope:

var stored_options = new Array;

function store_options(){    
    $('[id^="tagboxfv-"]').each(function(){
        var last_index = slice_last_index(this);
        $('[id="form-'+last_index+'"] > select[id="v-'+last_index+'"] > option').each(function(){
            stored_options[last_index] = [];
            stored_options[last_index][$(this).val()]=$(this);
        });
    });
}

As an alternative your function can have a return statement so you could use it anywhere you want (this way no global variables are introduced):

function store_options(){  
    var stored_options = new Array;  
    $('[id^="tagboxfv-"]').each(function(){
        var last_index = slice_last_index(this);
        $('[id="form-'+last_index+'"] > select[id="v-'+last_index+'"] > option').each(function(){
            stored_options[last_index] = [];
            stored_options[last_index][$(this).val()]=$(this);
        });
    return stored_options;
    });
} 
Alex Art.
  • 8,711
  • 3
  • 29
  • 47
  • Tried the first one but it only records the last option for the 2nd array i also tried the second one and it outputs undefined function fv_tags(){ var stored_options = store_options(); console.log(stored_options); }); – taptipblard Sep 07 '14 at 07:53
  • For the firstone - i think the problem is in slice_last_index(this) function - i assume that your indexes a overridden. Regarding the second one - you need to insure that store_options() defined in outer scope ( not inside $(document).ready ) and check out definition your fv_tags function as well – Alex Art. Sep 07 '14 at 08:08
  • your answer is right. my issue is with setting up the multidimensional arrays – taptipblard Sep 07 '14 at 08:47
0

You can use a variable outside all functions

    <script>
      var someVar;
      function foo(){

      }
    </script>

You could also set a property of the window and use it as you like i.e

       window.propName = "asd";