I am trying to do some proves with JavaScript
but I see a behaviour that I consider that it do not have to be like this. Here is my code:
Code:
<!DOCTYPE html>
<head>
<meta charset = "utf-8"/>
<title> Exercise prompt </title>
<script type = "text/javascript">
function disp_prompt()
{
var name = prompt("Please enter your name", "");
if(name != null && name != "")
{
document.write("Hi " + name + " How are you?");
}
}
</script>
</head>
<body>
<input type = "button" onclick = "disp_prompt()" value = "Show a prompt box." />
</body>
</html>
Expected result:
When I click on the button, the prompt appears and when I click the button "Accept", the sentence on the function document.write
have to be under the button.
Result:
When the prompt box
it is displayed and I press the button "Accept", the button dissappear and it is only shown the sentence on the function document.write
.
I can see on w3schools the following sentence:
Write some text directly to the HTML document
but I also could see another statement:
Using document.write() after an HTML document is fully loaded, will delete all existing HTML.
So I cannot understand the real purpose of document.write
. If you want to write some text on your HTML
... Why it has to remove the rest of the elements?
Is there a method to avoid that and to keep the rest of the elements on the HTML
?
Thanks in advance!