Is it possible to create new variables based off of user input? Ex: when a user enters something in a text box a new variable gets created that is named whatever they put in the text box.
You could use prompts:
var result = prompt("Prompt text");
No what I am trying to do is to make a new variable where the variable name is based off of user input
Yes, it is possible, but slightly complicated. Here is one way you can do it, using ‘this’.
this[prompt("Enter variable name")]=prompt("Enter variable value");
There is another solution using the eval() function.
eval("var "+prompt("Enter variable name")+"="+prompt("Enter variable value"));
If you aren’t in strict mode, you can omit the “var” part in the eval function because variables that are assigned values without been declared, automatically become global variables.
Both of these solutions do the same thing, by the way.
Ok thanks I’ll try that
A very simple way is to declare all the variables you need, but just declare them.
That way, you won’t worry about defining anything before user input.
Then when the user inputs something, you update the variable based on how you like.
yea but the thing is I need to create completely new variables basicly an infinite amount of times the user creates a new one. But the other answer should do ok. Thanks for responding though.