Standard
Standard

Reputation: 1512

Get variable via user input

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!

Upvotes: 0

Views: 53

Answers (4)

Nicolas Henrard
Nicolas Henrard

Reputation: 843

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');
        }
    })
});

Upvotes: 0

Frank ZHENG
Frank ZHENG

Reputation: 109

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"

Upvotes: 0

Abhitalks
Abhitalks

Reputation: 28387

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]);

Upvotes: 0

Barmar
Barmar

Reputation: 780843

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

var variables = {
    'money': '300$'
}
var input = 'money';
alert(variables[input]);

Upvotes: 2

Related Questions