PDA

View Full Version : Mind stopped working



vaibhav24in
02-12-2007, 10:16 AM
I am trying to add a script one of my page of my site but a error occouring while doing it. Actully i want to insert a prompt box before loading the page. I want the user insert his/her name in the prompt box and want to insert that name in the html coading of page. but as soon as i enter some name in the prompt box all the formatting of the page disappers like bg color and text color and every thing. here is my code
<html>
<head>
<script type="text/javascript">
function vaibhav()
{
var name=prompt("Please enter your name","Harry Potter")
if (name!=null && name!="")
{
document.write("Hello " + name + "! How are you today?")
}
}
</script>
</head>
<body onload="vaibhav()" value="Call function" bgcolor="#000000" text="#FFFFFF">>


</body>
</html>

shachi
02-12-2007, 10:23 AM
vaibhav24in: document.write() overwrites the whole page. Use <element>.innerHTML instead.



<html>
<head>
<script type="text/javascript">
function vaibhav()
{
var name=prompt("Please enter your name","Harry Potter")
if (name!=null && name!="")
{
document.getElementById("name").innerHTML = "Hello "+name+"!! How are you today??";
}
}
</script>
</head>
<body onload="vaibhav()" value="Call function" bgcolor="#000000" text="#FFFFFF">
<div id="name"></div>
</body>
</html>

mburt
02-12-2007, 11:05 AM
I would try to avoid the innerHTML method. Try the DOM way:

<html>
<head>
<script type="text/javascript">
function vaibhav()
{
var name=prompt("Please enter your name","Harry Potter")
if (name!=null && name!="")
{
var text = document.createTextNode("Hello "+name+"!! How are you today??")
var tname = document.getElementById("name")
while (tname.firstChild) {
tname.removeChild.firstChild
}
tname.appendChild(text);
}
}
</script>
</head>
<body onload="vaibhav()" value="Call function" bgcolor="#000000" text="#FFFFFF">
<div id="name"></div>
</body>
</html>