0

In this page javascript prompt works only if directly called in body section, if we try to call functions show() or showIN(), the first in head section, the second in body section, the var is undefined. Why ?

<!DOCTYPE html>
<html>
<head>
<script>
//called by button 2 "show" : doesn't work, u=undefined
function show(){
    var u = prompt("What 3 ?");
    alert("u = "+ u);
    alert("qu = "+ qu);
}
</script>

</head>
<body onload= "show();">
<script>
// this works:
var qu = prompt("What 1 ?");
    alert("qu = "+ qu);

// called by button two "showIN": doesn't work, w=undefined
function showIN(){
    var w = prompt("What 4 ?");
    alert("qu = "+ qu);
    alert("w = "+ w);
}
</script>

<button id = "one" onClick = "show();">show</button>
<br/>
<button id = "two" onClick = "showIN();">showIN</button>
</body>
</html>
ellebi3
  • 1
  • 1
  • 5
    Possible duplicate of [Where should I put – devlin carnate Oct 25 '19 at 17:42

1 Answers1

0

<!DOCTYPE html>
<html>
<head>

</head>
<body onload= "show();">
<script>
//called by button 2 "show" : doesn't work, u=undefined
function show(){
    var u = prompt("What 3 ?");
    alert("u = "+ u);
    alert("qu = "+ qu);
}
</script>
<script>
// this works:
var qu = prompt("What 1 ?");
    alert("qu = "+ qu);

// called by button two "showIN": doesn't work, w=undefined
function showIN(){
    var w = prompt("What 4 ?");
    alert("qu = "+ qu);
    alert("w = "+ w);
}
</script>

<button id = "one" onClick = "show();">show</button>
<br/>
<button id = "two" onClick = "showIN();">showIN</button>
</body>
</html>

You need to place script inside of Body not Head. Please check snippet.

George Wang
  • 441
  • 1
  • 11
  • Sorry but your answer has not fixed the problem: putting the script in the body section works as snippet on stackoverflow (vars u and w are changed by prompt() function) , but copying it as an HTLM file on my HD and reloaded it doesn't work: u and w are undefined. The problem arose because many old scripts of mine ceased to work properly after I don't know which modification of the behavior of the browsers. I use firefox (70.01) on linux and windows. – ellebi3 Nov 12 '19 at 09:57