0

I have a collection of arrays which are generated dynamically. What I am trying to do is to implement an AutoComplete functionality. I want to use those arrays in click event handler, by getting name dynamically and assigning that to local array. But that is not working (I'm not sure abt my code). Is there any way to achieve that?

Here is my code which I believe should work (which does not work):

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script>
 var ga_input1 = new Array('India','Russia','Norway');
 var ga_input2 = new Array('Delhi','Mumbai','Hyderabad');
</script>
<body>
 Countries: <input id="input1" type="text"/>
 Cities: <input id="input2" type="text"/>
 <script>
 var arrayTmp = new Array();
 $('input').keydown(function(){
 var id = $(this).attr('id');
 arrayTmp = "ga_"+id; // What I believe here is the values of ga_input1/ga_input2 are assigned to array 'arrayTmp' 
 //alert(arrayTmp[0]);
 });
 </script>
</body>
bezmax
26.3k11 gold badges56 silver badges84 bronze badges
asked Mar 26, 2012 at 9:42

4 Answers 4

1

All global variables are members of the window object, so:

arrayTmp = window["ga_"+id];

But I'd personally put the data in an object like this:

data = {
 'input1': ['India','Russia','Norway'],
 'input2': ['Delhi','Mumbai','Hyderabad']
};
...
arrayTmp = data[id];
answered Mar 26, 2012 at 9:52
Sign up to request clarification or add additional context in comments.

Comments

1

You can put that arrays in a "Map" and later fetch them from it easily.

Here's how it's done:

var countryMap = {};
countryMap["Europe"] = ['Russia', 'England', 'Norway'];
countryMap["America"] = ['USA', 'Canada', 'Mexico'];
....
var arrayTmp = countryMap["America"];
alert(arrayTmp[0]); //USA
alert(arrayTmp[1]); //Canada
alert(arrayTmp[2]); //Mexico
answered Mar 26, 2012 at 9:52

Comments

1

What you have in arrayTmp is just a string "ga_input1". Instead, try eval("arrayTmp=ga_"+id);.

answered Mar 26, 2012 at 9:55

Comments

0

eval('var arrayTmp = ga_' + id); alert(arrayTmp[0]);

answered Mar 26, 2012 at 10:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.