Alert is not displayed

0

I do not understand why the alert is not displayed

<!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>
    
asked by Alex 07.04.2016 в 23:03
source

1 answer

2

It is probably showing 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 Console tab there you will see the javascript error that I mention.

What I see is that if the alert should be displayed when the button is pressed the alert should be within the function

function validar(){
  var str = document.getElementById("texto").value;
  alert(str);
}
<!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>
    
answered by 07.04.2016 / 23:08
source