How to create a dynamic variable

Asked

Viewed 6,684 times

4

I have a field(input text), and would like to get the value, and pass as variable.

In other words, pass the value of this text field into the:

var valor do campo aqui ;

See the example I leave:

<script language="javascript">
<!--
var nome
nome = window.prompt("Digite o nome para variável:");
document.write("var " +nome+ ";<br>");
//-->
</script>

This example gives a clear idea. The real intention is that, the result is included at runtime, in the source code, set as variável within the function exemplo(){ var +nome+ = "valor"; }; and/or function exemplo(){ var valor = "+nome+" };. It would be something like an id(identifier) that would receive any value.

I have elaborated this more concrete example as follows:

<script language="javascript">
 <!--
  var nome 
  nome = window.prompt("Digite o nome:");
  variavel = document.createElement('script');
  variavel.textContent = nome; 
  document.getElementById("id").appendChild(variavel);
 //-->
</script>

But, I can only create HTML elements, nothing functional for purpose, in which I need to incorporate directly into the source code of the open page within the script.

I hope I’ve been clear. I appreciate your help, since.

  • Hello Diego. The question is unclear. You have one <input type="text"> correct? and then you want the value inserted there to go to a variable right? you can explain better what happens next?

  • Diego, jump in here: http://chat.stackexchange.com/rooms/25038/javascript

  • I added an answer below, to see if it helps. If you have problems accessing chat because your browser downloads Chrome or Firefox and tests again.

  • Are you sure you need to create variables with the dynamic name like this and it would not be enough to use fields from a global table, like var minhatabela = {}; minhatabela[nomedocampo] = valordocaompo? If you quit overwriting global variables you always have a chance to spoil the value of some existing variable.

3 answers

4

The method eval(); is an option. Perhaps the only answer here that will work for the non-global variables. Although eval(); should not be used in this case as there are better methods.

Speaking of better methods you can use the object window has a reference to all global variables and global functions you are using.

But if you don’t want to use one method eval(); or object window. you can try something like this:

<script language="javascript">
 <!--
 var obj = {}; 
 obj['teste'] = 'Não há mais necessidade de armazenar em um objeto global.\nO segredo fica por conta do acesso a propriedades via string.'; 
 alert(obj['teste']); 
 //-->
</script>

In Javascript these two are equivalent: obj.teste = 'valorString' obj['teste'] = 'valorString'

To illustrate a little better the operation of some of these methods/objects, created examples that use some examples to demonstrate the use of dynamic variables

Example 1

<script language="javascript">
 <!--
 var nome;
 nome = window.prompt("Digite o nome:");
 var x = nome;
 var valor = 'x';
 // resultado
 alert(eval(valor)); 
 //-->
</script>

Example 2

<script language="javascript">
 <!--
 var nome;
 nome = window.prompt("Digite o nome");
 var x = 'valor';
 str = x+' = '+'nome';
 eval(str);
 // resultado
 alert(valor);
 //-->
</script>

If you need to create dynamic variables in Javascript, and you don’t know how many variables you’ll need. Use the syntax for, make a loop with the method eval();. The method eval(); receives as parameter a String which will be executed as if it were a command. See:

Example 1

<script language="javascript">
 <!--
 var nome;
 nome = window.prompt("Digite o nome:");
 for(var i = 1; i <= 3; i++)
 { 
 window['v' +i] = "var " + i; 
 } 
 // recuperando as variaveis 
 alert(v1); // variavel 1 
 alert(v2); // variavel 2 
 alert(v3); // variavel 3 
 //-->
</script>

Example 2

<script language="javascript">
 <!--
 //criando variável dinâmica
 var valor;
 valorTeste = window.prompt("Digite o nome:");
 for(var i = 0; i < 3; i++) {
 eval("nome" +i+ " = '"+valor+"';");

 //recuperando os valores dessas variáveis
 alert(window["nome" +i]);
 }
 //-->
</script>

Example 3

Now, let’s create dynamic variables using the object window javascript:

<script language="javascript">
 <!--
 //criando algumas variáveis dinamicamente
 for (var i = 0; i < 5; i++)
 {
 window["nome" + i] = i + 10;
 }

 //recuperando os valores dessas variáveis
 for (var i = 0; i < 5; i++)
 {
 alert(window["nome" + i]);
 }
</script>

Example 4

<script language="javascript">
 <!--
 //criando variável dinâmica
 var nome;
 nome = window.prompt("Digite o nome:");
 for(var i = 0; i < 3; i++) {
 alert(eval+"(var "+nome+i+" = '"+i+"';)");
 }
 //-->
</script>

These examples are very simple, although impractical.

1


If I understand your question you want to create a script, and at least one variable whose name is defined by a <input> in HTML. Then you want to insert this script into the page so that you can see with the browser tools.

I think this is what you’re looking for:

function addScript(varname) {
    var script = document.createElement('script');
    script.innerText = 'var ' + varname + ' = 10; alert(' + varname + ');';
    document.body.appendChild(script);
}

var input = document.querySelector('input');
var button = document.querySelector('button');
button.addEventListener('click', function(){
	var name = input.value;
	addScript(name);
});
<input type="text">
<button>testar</button>

jsFiddle: https://jsfiddle.net/g4vfdsj1/

What this script does is expect the button is clicked, then fetches the input value, then calls a function to whom you pass the input value, then creates a script element and inserts the input value and then inserts it into the DOM.

0

In Html do the following:

<input type="text" id="seuInput"  onkeyup="keyupFunction()">

In javascript:

function keyupFunction() {
   var valor_do_campo_aqui = document.getElementById("seuinput").value;
}
  • The author of the question wants to create a "dynamic variable". I think you want something like window[input.value] = 'foo';... I invited you to chat. Let’s see if the question becomes clearer.

  • 1

    @Sergio Valeu for the tip, I didn’t see that you had posted a link I was still writing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.