views:

108

answers:

4

I'm wondering if it's possible to enter a value of a variable into a prompt box have it return to me in an alert of its original variable.

Say: var myGoal = "answer"; If I enter "answer" into a prompt, what would a good method be of taking my value of "answer" ,searching, and having it return myGoal in an alert?

A: 
function test() 
{
    var answer = prompt("Hello? What is your name?",'');
    alert(answer);
}
Chris Kloberdanz
Heh, close. I phrased it rather poorly. I mean is there a method of taking exactly what I type into the prompt, searching for that value(string/number) and returning its variable.Say: var myGoal = "answer";If I enter "answer" into a prompt, what would a good method be of taking my search value of "answer" and having it return myGoal in an alert?
Francis
A: 

The only way to achieve what you wish is through use of the eval function. Eval is also known as the "evil" function. It can introduce massive security holes to your code and is extremely inefficient. Do not use eval.

The problem is that a value assigned to a variable will always be a string, number, boolean, undefined, array, function, or object literal. You cannot assign a variable name to a another variable as a value, because when one variable is assigned to another the contents of the variable are what is actually assigned.

You are going to have to redesign the test you are trying to write to test against the supplied value explicitly instead of converting a string into a variable name.

+2  A: 

Something like this would do the trick:

function test(val)
{
    for (var i in window)
    {
        if (window.hasOwnProperty(i) && window[i] === val)
        {
            alert(i);
        }
    }
}

This basically iterates though everything in the global object (window), and fires off an alert when it finds one that equals the value you're looking for.

ShZ
+1  A: 

If you're willing to change your approach slightly:

var Data = new Object();
Data["myGoal"] = "answer";
// ...

// Get response from prompt...
var response = /* ... */;

for (var key in Data)
{
    if (Data[key] == response)
    {
        alert(key);
    }
}
bobbymcr