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);
        });
    });
}
1

2 Answers 2

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;
    });
} 
Sign up to request clarification or add additional context in comments.

3 Comments

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); });
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
your answer is right. my issue is with setting up the multidimensional arrays
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";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.