Getting a Global Array to work in a Function

I recently spent a lot of time debugging this code i was working on for what I thought would be a simple onchange event.

The Issue:
I have sizes and colors, but not all sizes are available in all colors, so onchange of the color select box, i need to load the correct size options select box.

Between a lot of back-end manipulation, I was able to create my front-end JS arrays of colors with the sizes that are available. I ran into the issue that my passed in variable to the function was becoming the array, instead of calling the array.

For example, If I passed in “BLK” for Black, I was getting:

array[0] =>B
array[1] =>L
array[2] =>K
array[N] => undefined

where the Nth options looped through undefined until my for loop for the options of my color box’s length had been reached.

The Solution:
After scratching my head for hours and trying 232132 things, It turns out all I needed to do was to use the eval() function to evaluate my variable first, instead of treating it like a literal string.

Here’s the completed working source:

function popsizes(colorcode) {

var BLK= ["2XL","3XL","4XL","5XL","LG","MD","SM","XL","XS"];
var WH= ["LG","MD"];
// etc, many more color arrays

elem = document.getElementById("selcolor");
sizelist = eval(colorcode);

for (i=0; i<elem .options.length; i++) {
  document.getElementById("selsize").options[i] = new Option(sizelist[i]);

That script is powered by the onchange event from the form:

    <select "id="selcolor" name="color" onchange="popsizes(this.options[this.selectedIndex].value);">
      <option value="WH">White</option>
      <option value="BLK">Black</option>
      <option value=""> Many more colors, etc .... </option>
    <select "id="selsize" name="size">
      <option value="">Select Color First</option>

This entry was posted in Programming and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>