views:

59

answers:

2

Is there any way to convert a string to a variable in Javascript? Right now, what I have is a script that updates data based on the values of the select box:

<script type="text/javascript">
var a = new Array();
a[0] = 'Name';
a[1] = 'Description';

var b = new Array();
b[0] = 'Name 2';
b[1] = 'Description 2';

function changeSystem(){
    var selectedAccount=document.getElementById('selected_option').value;

    document.getElementById('name').innerHTML = selectedAccount[0];
    document.getElementById('description').innerHTML = selectedAccount[1];
}
</script>
<form method="POST">
    <select onchange="changeSystem()" id="selected_option">
     <option>A</option>
     <option>B</option>
    </select>
</form>
<span id="name"></span><br>
<span id="description"></span><br>

selectedAccount is the string of the chosen element in <select>. However, for it to access the array, it needs to be a variable, i.e. a[0] instead of 'a'[0]. What solutions are there to this?

+4  A: 
var dict = {
    'A': ['Name', 'Description'],
    'B': ['Name 2', 'Description']
};

dict['A'][0]

So dynamically access it with

dict[selectedAccount][0]

You can use an object literal instead of an array:

var dict = {
    'A': {'name': 'john'}
};

dict['A']['name']
meder
+3  A: 

I would use something like that:

<script type="text/javascript">
var stuff = { 
    A: { name: 'Name', desc: 'Description'},
    B: { name: 'Name 2', desc: 'Description 2'}
};

function $(aId) {
    return document.getElementById(aId);
}

function changeSystem(){
    var selectedAccount = $('selected_option').value;

    if (selectedAccount in stuff) {
        $('name').innerHTML = stuff[selectedAccount].name;
        $('description').innerHTML = stuff[selectedAccount].desc;
    } else {
        $('name').innerHTML = '';
        $('description').innerHTML = '';
    } 
}
</script>
<form method="POST">
    <select onchange="changeSystem()" id="selected_option">
        <option>A</option>
        <option>B</option>
        <option>C</option>
    </select>
</form>
<span id="name"></span><br>
<span id="description"></span><br>

Tested on: Google Chrome 6.0.427.0 dev

RC
Odd I didn't see meder answer when posting mine :?
RC
JSON? I guess you mean Object Literal Notation? http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/
Sean Kinsey
@Sean, Thanks for the link.
RC
@RC, then can you please correct your answer? Neither OLN or JSON need be mentioned here, especially not JSON.
Sean Kinsey