The var is not saved in js

3

I have the following code in js, which does not save the input information in the variable. At the time of activating the function show () it returns me that the variable x is not defined

function crear(){
	var x = document.getElementById("name").value;
	}
function mostrar(){
	document.getElementById("demo").innerHTML = x;
	}
<input type="text" id="name">

<button onclick="crear()">Crear</button>
<button onclick="mostrar()">Mostrar</button>
<h1 id="demo"></h1>
    
asked by Tefef 03.08.2018 в 16:49
source

5 answers

3

You have a problem of englobamiento of the variable, in the crear() you are declaring the variable there, then it can only be visible within that function.

The solution is to declare the variable outside the function.

var x;

function crear(){
	x = document.getElementById("name").value;
}
function mostrar(){
	document.getElementById("demo").innerHTML = x;
}
<input type="text" id="name">

<button onclick="crear()">Crear</button>
<button onclick="mostrar()">Mostrar</button>
<h1 id="demo"></h1>
    
answered by 03.08.2018 / 16:55
source
4

It is because of the scope of the variable. The scope is where the variable exists. In this case, it only exists within the function. To be able to do what you want, you need a global variable.

var x = ''; //variable global

function crear(){
  var l = ''; // variable local.
	x = document.getElementById("name").value;
}
function mostrar(){
  // console.log(l) // esto no funciona ya que no es su ambito y es local de la otra funcion
	document.getElementById("demo").innerHTML = x;
}
<button onclick="crear()">Crear</button>
<button onclick="mostrar()">Mostrar</button>
<h1 id="demo"></h1>
<input id='name'>
You have more information about the fields here     
answered by 03.08.2018 в 16:57
2

You are not saving the value in the variable since "x" is a local variable of the function create (), so it is not accessible from show (). One option is to declare "var x" as a global variable. Greetings!

var x;
function crear(){
  x = document.getElementById("name").value;
}
function mostrar(){
  document.getElementById("demo").innerHTML = x;
}
    
answered by 03.08.2018 в 16:57
1

This is because you have two functions and the variable x is outside the context of the show function. You could call the content directly in the show function.

function mostrar(){
var x = document.getElementById("name").value;
document.getElementById("demo").innerHTML = x;
}
    
answered by 03.08.2018 в 16:54
0

It is because the variable 'x' does not exist in the function show, a solution would be to pass it by parameter, or that the variable 'x' is global.

function crear() {
  var x = document.getElementById("name").value;
  mostrar(x)
}

function mostrar(x) {
  document.getElementById("demo").innerHTML = x;
}
<input type="text" id="name">

<button onclick="crear()">Crear</button>
<button onclick="mostrar()">Mostrar</button>
<h1 id="demo"></h1>
    
answered by 03.08.2018 в 16:55