I don't understand why the alert is not shown
<!DOCTYPE html>
<html lang="en">
<head>
<title>Prueba</title>
</head>
<body>
<br>
<input type = "text" id = "texto" ></imput><br>
<input type = "button" value = "boton" onclick = "validar()"></imput>
</body>
</html>
<script>
function validar(){
var str = document.getElementById("texto").value;
}
alert(str);
</script>
Surely it is being displayed when the page is loaded, but since the variable
str
is not defined globally, a javascript error is generated.If you access the developer tools of the browser, with the F12 key, you could analyze the tab
Console
there you will see the javascript error that I mentioned.What I see is that if it
alert
should be displayed when the button is pressed the alert should be inside the function