I have the following code in js, which does not save the input information in the variable. When activating the show() function, 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>
It's because of the scope of the variable. The scope is where the variable exists. In this case it only exists inside the function. In order to do what you want you need a global variable.
You have a variable enclosing problem, where
crear()
you are declaring the variable there, so it can only be visible inside that function.The solution is to declare the variable outside the function.
You are not saving the value in the variable since "x" is a local variable of the create() function, so it is not accessible from display(). One option is to declare "var x" as a global variable. Cheers!
This is because you have two functions and the variable x is outside the context of the display function so you could call the content directly in the display function.
It is because the variable 'x' does not exist in the show function, a solution would be to pass it as a parameter, or that the variable 'x' is global.