why does document.write clear the page?

Joined
12 Feb 2006
Posts
17,545
Location
Surrey
got it so that the user clicks a button then inputs a load of information and then a load of ifs and elses decide on the outcome and if its a valid answer document.write will display some information, the annoying thing is that its clearing the whole page and replacing it with the information.

why is it doing this and not just displaying the
information in it's correct place and how do i stop it?
 
here it is, remember only first time i really gone into javascript so if it's an old thing to do sorry. Loving learning js though, some cool stuff.

Code:
<html>

<head>

<script type="text/javascript">



</script>




</head>

<body>

<script type="text/javascript">

var chest = "0" 

function chestcheck( )

{

chest=prompt("What Chest size are you in inchs? Ranges from 34-46")



  if (chest < 34 )

    {
      alert("The size you chose is incorrect, Please choose a size between 34 and 46 inchs.")
    }

      else if (chest >= 34 && chest <= 37)

        {
          document.write("Your chest size is Small. The size you chose is " + chest)
        }

          else if (chest >= 38 && chest <= 41)

            {
              document.write("Your chest size is Medium. The size you chose is " + chest)
            }

              else if (chest >= 42 && chest <= 46)

                {
                  document.write("Your chest size is Large. The size you chose is " + chest)
                }

                  else if (chest > 46)

                   {
                      alert("The size you chose is too big. Please restart and choose a size between 34 and 46 inchs")
                    }
                    
}

</script>


<input type="button" value="Chest Check"
onclick="chestcheck()" >


<p>

hello world

</p>


</body>

</html>
as you can see it clears the hello world. I though it was because the script is in the head section but that didn't make a difference anyway. The only thing i can think of though is because the document.write has no where to produce the results except after the button but i can't see how you'd do it any differently?

thanks

also while its here why does the page continue to load something after you have run the script and then you can't refresjh the page either?
 
Last edited:
I had a quick look through and couldn't see anything particularly wrong with it. I'm a bit busy at the moment, but I quickly rewrote the entire script how I would have done it, and it works fine.

So here it is, it's not any more complicated than your version really. Hope it helps, and if there's anything you want to know, feel free to ask :D

Code:
<html>
<head>

</head>

<body>
<script type="text/javascript">
var chest = "0" 
function docheck(inval)
{

 if (inval < 34 )
    {
      alert("The size you chose is incorrect, Please choose a size between 34 and 46 inchs.")
	document.getElementById("span1").innerHTML="Please try again.";
    }

else if (inval >= 34 && inval <= 37)
        {
	  writestr="Your chest size is Small. The size you chose is " + inval;
          document.getElementById("span1").innerHTML=writestr;
        }
else if (inval >= 38 && inval <= 41)

            {
	  writestr="Your chest size is Med. The size you chose is " + inval;
          document.getElementById("span1").innerHTML=writestr;
            }

else if (inval >= 42 && inval <= 46)

                {
	  writestr="Your chest size is Large. The size you chose is " + inval;
          document.getElementById("span1").innerHTML=writestr;
                }

else if (inval > 46)

                   {
                      alert("The size you chose is too big. Please restart and choose a size between 34 and 46 inchs")
	document.getElementById("span1").innerHTML="Please try again.";
                    }
return false;                  
}
</script>


<input type="button" value="Chest Check" onclick="docheck(prompt('What chest size are you in inches? Ranges from 34-46'));" >


<p>
hello world
</p><br>

<span id="span1">
</span><br>

</body>
</html>

Jon
 
the difference is that document.write clears the screen and writes what you choose to it - you need, as GeForce pointed out, to find the element that you want to change the content of and use innerHTML to print your message to.
 
thanks that worked just write. few questions though if you could explain would be great.

so getElementById is that like the write part of document.write? does it need to be caps lock on all words except the first? what similiar things are there like this? like for instance is there getElementByDate or does it not work like that?

aswell with the innerHTML and writestr im not 100% sure what these meanif a beter explaination could be given? i see the results but not sure what its doing to get the results if that makes sense and would you'd call these things.

think thats it. thanks for the help folks. Like i say i see whats going on but i am only seeing and not fully understanding.

[edit]
oh and also why the return false? i remember reading about doing that in c++ aswell but forget why? im going to go read a load more tutorials i think
 
Last edited:
Hi mate. I'll try and answer everything!

so getElementById is that like the write part of document.write? does it need to be caps lock on all words except the first? what similiar things are there like this? like for instance is there getElementByDate or does it not work like that?
It doesn't work quite like that. Element IDs are used in CSS amongst other things. Ie. you can give any element in a page an "id", and then CSS or JavaScript can access contents or properties of that element by using the "getElementById" method of the document object. Yes, capitals are important!

For example:

<form name="form1">
<input type="button" name="button1" id="mybutton" value="Button">
</form>


This button could now be accessed via JavaScript in either of the following two ways:
document.form1.button1;
or
document.getElementById("mybutton");


aswell with the innerHTML and writestr im not 100% sure what these meanif a beter explaination could be given? i see the results but not sure what its doing to get the results if that makes sense and would you'd call these things.
innerHTML is a property of any HTML object on a page. It is part of the Document Object Model which allows JavaScript to "see" and change the HTML inside an element. Again, capital letters do matter.

For example:

<span id="myspan">blah blah blah</span>
If we then used this JavaScript code:
var spancontent = document.getElementById("myspan").innerHTML;
the variable "spancontent" would now equal "blah blah blah".

we can also do the following:
document.getElementById("myspan").innerHTML="Hello world";
Then the "blah blah blah" that was on the page would then change to "Hello world".

"writestr" is just a variable ;) It just makes the code a bit easier to read, without there being 's and "s all over the place!

oh and also why the return false?
To be honest, you don't really need it. But since the function is called from a user input (ie. clicking the button) and a variable is sent to the function (chest size, called 'inval' in the function), the event handler will normally expect a value to be returned from the function. By sticking return false; at the end, you return a null value. Which means the event handler is happy and won't throw exceptions in older browsers.

Hope that helped :)

Jon
 
Last edited:
No problems!

For dynamic pages, and things like AJAX if you ever move onto that, getElementById and innerHTML are extremely useful. A quick Google will get you some more in-depth tutorials on them :)

Jon
 
the dom is such a useful thing to have under your belt when developing for the web - and for some reason, I find it really fun writing javascript. this is a really good resource that tells you all the properties and methods associate with different parts of the dom. it's also useful to know about javascript/html event handlers, too - such as onclick, onselect, onblur, onfocus etc, as they are used to trigger javascript functionality in a page.

that previous link might seem a bit daunting at first, but I'll give you a little intro to hopefully help you out a bit.

as GeForce said, you can assign an html element (javascript knows this as an object) to a variable to cut out confusion and make your code cleaner. once you assign this html element, javascript gives it properties and methods to alter pretty much everything about that element, as well as any elements that are contained within it, and any element that contains it. it is possible, though potentially quite messy, to get from any element on your page, to any other using the javascript dom - so it's very useful. I'll show you a broken down version of something I wrote yesterday to give you an idea of what I'm talking about.

In my page, I have a <ul> tag, with multiple <li>s in it. In each <li>, there's an <a> tag. depending on the url of my current page, the class (ie. style) of the link needs to change to reflect that it's the current page. as well as that, the link needs to be unclickable (don't know why, specifically, but I do as I'm told :p). The code looked something like this:

Code:
function highlightMenu() {
	var nav = document.getElementById('navigation');
	for (i=0;i<nav.childNodes.length;i++) {
		//we'll assume that I've written my html VERY tidily, as javascript interprets white space as a text object!
		var item = nav.childNodes[i];
		//again, assuming that the first child node is the link we're looking for, to make this clearer
		var alink = item.childNodes[0];
		if (alink.href == document.location) {
			//take the link text so that it can be used later
			var linktext = alink.innerHTML;
			//remove the link, for some reason!
			item.removeChild(alink);
			//give the list item a different class so that it's obvious what page you're on
			item.className = 'selected';
			//use the link text from the now destroyed link so that your menu doesn't look confused
			item.innerHTML = linktext;
			//stop the script running, as you've already achieved what you set out to do
			return true;
		}
	}
}

that might be totally unhelpful, but it gives you an idea of what can be achieved :)
 
Back
Top Bottom