Good friends and thanks in advance. Well, that said, I don't know why this GetElementById doesn't work. It does not collect the data in the constant
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="" id="formulario">
<input type="text" id="texto" placeholder="ingrese el texto">
<input type="submit" value="submit" id="boton">
</form>
<script>
const contenido = document.getElementById("texto").value;
function mostrar(){
alert(contenido);
}
boton.onclick = mostrar;
</script>
</body>
</html>
You are getting the value of the input
"texto"
on page load. Any subsequent changes are not detected. You can fix it by moving that line to the functionmostrar
:On the other hand, I recommend you not to use the global variable
boton
: although it works in all browsers, it is accepted by the standard as an inherited functionality that is maintained for backward compatibility, but it is not advisable to use it (it will probably be removed over time, in future versions). of the standard). Instead I recommend you define it yourself:The reference to
input
is not in the context ofmostrar()
, so it does not get the value.Apart from what @PabloLozano tells you, it's always a good idea to put your code inside the listener
DOMContentLoaded
, to wait for the entire DOM to be loaded before using any element of it. This, apart from being the best practice, helps to understand how to organize the code.If, for example, you need to refer to the element
input
in various parts of your code, you can create a reference to it inside the listenerDOMContentLoaded
and then use that reference to get the value where you need it.For example here we create a reference to the element in the constant
elContenido
and then, inside the function we callelContenido.value
. Thus, within any function that needs that value, you will only have to useelContenido.value
, obtaining the value that the element has at that moment . The element is constant in the DOM, but the element's value can change, so you should callvalue
it where you need it .Just wanted to add/clarify that being
<script>
before the completion ofbody
is going to be executed after all the content ofbody
has been loaded. This means that the query(getElementById
) could be outside the function, and in fact it is preferable so that it does not perform the same evaluation on each click. What cannot be outside is.value
, because otherwise we only have the initial value. Example: