-2
I know there is scope in javascript but in this case it is different the variable it is global follows the example.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style1.css">
<title>Document</title>
<script src="js/js.js"></script>
</head>
<body>
<input id="input1" type="text" value="">
<p id="paragrafo"></p>
<button type="button" id="button1">Click</button>
<script>
function myFunction() {
var name1 = document.getElementById("input1").value;
document.getElementById("paragrafo").innerHTML = name1;
}
document.getElementById("button1").addEventListener("click", myFunction);
</script>
</body>
</html>
Note that the code so far works perfectly when you click on the button the value inside the input
is returned to the paragraph with id="paragrafo"
but when the variable is placed outside the function the button can’t pick up its value only if it is inside the function. I know the problem is very simple I stayed a few months without using javascript and I forgot more who can help I am very grateful.
variables within functions are not global, your question is your answer
– Davi Wesley
What variable? If you have a problem with a code other than this one it would not be the case to post the other code and not the one you have no problem with?
– Maniero
@David, but if the variable
name1
was declared out of function, it would be global, and you could access it within function, agree? I think this is not Fernando’s problem, the question is not clear, but I believe he is starting the variable outside the function, and then expecting it to be updated as the value of the input is changed, as if it were a reference. Since this does not happen, he thinks he is not able to access it. But this is just a guess.– Andre
yes, my question was about the variable in the code it is as a variable that is only valid within its scope so it becomes local, but when I put it out it becomes global this is the problem in my question makes reference to the global variable not the local I sampled the code for you to see that it is working perfectly but when placing the variable outside the function the button does not access it even being it global.
– Leandro Nascimento
Because my problem was related to these language if you know java or php would surely solve the problem
– Leandro Nascimento