tags:

views:

500

answers:

3

Im trying to accomplish something "like" this. I want to add the text stored in some JS variables into the doc based on the value selected in a combo. i.e. how do I reference JS variables based on the selected value of a combo?

<select id="clickMe">
    <option value="a">a</a>
    <option value="b">b</a>
    <option value="c">c</a>
</select>

<span id="attachHere"></span>   

<script>

var a = "something about a";
var b = "something about b";
var c = "something about c";

$(document).ready(function() {
    $("#clickMe").change(function() {
        $("#attachHere").text($("#clickMe").val());
    });
});


</script>
+3  A: 

It'd be better if you used arrays objects.

Assuming you don't want to use arrays, I think you can use eval:

$(document).ready(function() {
    $("#clickMe").change(function() {
        var tmp;
        eval('tmp = ' + $("#clickMe").val());
        $("#attachHere").text(tmp);
    });
});
strager
I'd recommend the arrays too. But nice one with the eval().
lpfavreau
Yeah cool. The eval() worked but I gotta give the answer to lpfavreau
+4  A: 

Why not go with something like that instead?

<script>
<!--

var values = {
    'a' : "something about a",
    'b' : "something about b",
    'c' : "something about c",
};

$(document).ready(function() {
    $("#clickMe").change(function() {
        $("#attachHere").text(values[$("#clickMe").val()]);
    });
});

//-->
</script>

You'll control your list of values and easily be able to add and remove values.

lpfavreau
+2  A: 

Try putting the values in a hash keyed by the choice and then extracting it based on the chosen value.

var choices = {};
choices['a'] = 'something about a';
choices['b'] = 'something about b';
choices['c'] = 'something about c';

$(document).ready(function() {
    $("#clickMe").change(function() {
        $("#attachHere").text(choices[$(this).val()]);
    });
});
tvanfosson