0

I want that the user can see the value of a variable by writing it's name in a textarea, simpliefied:

var money = "300$";
var input = "money"; //user wants to see money variable

alert(input); //This would alert "money"

Is it even possible to output (in this example) "300$"?

Thanks for help!

4 Answers 4

2

Instead of seprate variables, use an object as an associative array.

var variables = {
    'money': '300$'
}
var input = 'money';
alert(variables[input]);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use an object and then define a variable on the go as properties on that object:

var obj = {}, input;

obj.money = "300$";
input = "money";
alert(obj[input]);

obj.anotherMoney = "400$";
input = "anotherMoney";
alert(obj[input]);

Comments

0

A simple way,you can still try this one :

 var money = "300$";
 var input = "money"; //user wants to see money variable

 alert(eval(input)); //This would alert "money"

1 Comment

It's unwise to use eval on unfiltered input. Also, the comment next to your final line of code is not true.
0

Here is an answer who use the textarea as asked.

JSFiddle http://jsfiddle.net/7ZHcL/

HTML

<form action="demo.html" id="myForm">
    <p>
        <label>Variable name:</label>
        <textarea id="varWanted" name="varWanted" cols="30" rows="1"></textarea>
    </p>
    <input type="submit" value="Submit" />
</form>
<div id="result"></div>

JQuery

$(function () {
    // Handler for .ready() called.
    var variables = {
        'money': '300$',
            'date_now': new Date()
    }
    //Detect all textarea's text variation
    $("#varWanted").on("propertychange keyup input paste", function () {
        //If the text is also a key in 'variables', then it display the value
        if ($(this).val() in variables) {
            $("#result").html('"' + $(this).val() + '" = ' + variables[$(this).val()]);
        } else {
            //Otherwise, display a message to inform that the input is not a key
            $("#result").html('"' + $(this).val() + '" is not in the "variables" object');
        }
    })
});

Comments

Your Answer

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.