0

I have the following Javascript code:

<script>
    function slboxchg()
    {
        if(document.getElementById("slbox").value != 0)
        {
            var x = 'a'+document.getElementById("slbox").value;
            alert(x);
        }
    }
</script>

<script>
    var a1 = "1,2,3";
    var a2 = "3,4,5";
</script>

<select id='slbox' onchange='slboxchg()'>
    <option value='0'>None</option>
    <option value='1'>Apple</option>
    <option value='2'>Banana</option>
</select>

When I select "Apple", I expected the alert box show "1,2,3", but it showed "a1" instead.

Thank you for your time.

mattjegan
  • 2,724
  • 1
  • 26
  • 37
John
  • 109
  • 1
  • 10

3 Answers3

3

Instead of:

alert(x);

Try:

alert(window[x]);

Here's a CodePen Demo

Dan Kreiger
  • 5,358
  • 2
  • 23
  • 27
  • Is that a cross browser thing? – Richard Housham Jul 19 '17 at 09:48
  • This answer would be improved if you explained what you were doing and why the OP's code didn't work. – gaynorvader Jul 19 '17 at 09:49
  • No problem :) Glad I could help - basically were calling `alert` on a string, which will only alert the string - you can access it instead from the `window` object. You could also create your own object and access it from there. – Dan Kreiger Jul 19 '17 at 09:51
0

So what happens when we select "Apple"? The onchange event is called which triggers slboxchg() which in turn checks that the value is not 0, which is it since 1 != 0.

The variable x is then defined as the string containing the letter 'a' plus whatever is the value of the element. This value also happens to be a string, so what we actually get is x = 'a' + '1' which is just a string concatenation which returns x = 'a1'.

mattjegan
  • 2,724
  • 1
  • 26
  • 37
0

Lets do this a different way.

<script>
    var ar = ["0","1,2,3","3,4,5"];
    </script>

<script>
function slboxchg()
{
  if(document.getElementById("slbox").value != 0)
  {
    var x = ar[document.getElementById("slbox").value];
    alert(x);
  }
}
</script>



<select id='slbox' onchange='slboxchg()'>
<option value='0'>None</option>
<option value='1'>Apple</option>
<option value='2'>Banana</option>
</select>
Richard Housham
  • 1,525
  • 2
  • 15
  • 31
  • This line, might be needed var x = element.options[element.selectedIndex].value; It's been a while since I used pure javascript for this. Normally use jquery – Richard Housham Jul 19 '17 at 09:44