document.write and problems with how it overwrites existing code

A

Andrea

Hi there -

I'm hoping someone can help me; I've been struggling with this for a
few days! :)

I have a webpage that is comprised of many forms containing questions.
As the user answers one of the questions, that form is hidden and the
next is displayed. Also, as the user answers each question a "count"
variable is updated based on their response. I would like the question
to show up on the left side and the answer to show up in the upper
right hand corner. But, when I try to get the count to display using
document.write, it overwrites the existing form on the left.

I've pasted a simplified version of the code below (with comments).

I appreciate all help - I'm at a loss!
THANKS,
Andrea


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">

<style type="text/css">
#all_forms form {display: none; border: 1px solid black; width: 80%;
padding: 5px; background-color: gray;}
#all_forms form button {padding: 5px; margin: 5px;}
#currency {position: absolute; left: 80%; top: 10px; display: none;
background-color: #ECF5E2; }
</style>

<script type="text/javascript" language="javascript">
var count=0;
function calculate_priv(form_id, num_to_add, last)
{
if (last=="no") //not on last question, progress to next
{
count=count+num_to_add;
ques_num=form_id.charAt(form_id.length-1); //get the number of the
question
document.getElementById(form_id).style.display = "none"; //hide current
question
ques_num=parseInt(ques_num); //convert string to number
ques_num = ques_num+1;
form_id='ques' + ques_num;
document.getElementById(form_id).style.display = "block"; //display the
next form
}
else //on last question
{
count=count+num_to_add;
document.getElementById(form_id).style.display = "none"; //hide current
question
document.write("<p>Your final balance in the piggy bank is $" + count +
".</p>");
}
}

function write_currency()
{
//document.write("<div id='currency'>Balance in the Piggy Bank: $"
+count+ "</div>"); IF I TRY TO WRITE THE HTML HERE, IT OVERWRITES THE
FORM AND ONLY THE AMOUNT SHOWS.
document.getElementById("currency").style.display = "block";
}

</script>
</head>

<body>

<div id="introduction">It can be useful to think of this in terms of
currency. The following set of questions will allow you to fill or take
away from your
"piggy bank." You should answer the questions honestly based on your
own experiences. At the end you will find out the amount of currency in
your "bank."<br />
<form>
<button onclick="javascript: write_currency();
document.getElementById('ques1').style.display='block';
document.getElementById('introduction').style.display='none';">Calculate
my Currency</button>
</form>
</div>

<div id="currency">
<strong>Balance in the Piggy Bank: </strong>Needs to update with the
count variable<!--THIS IS WHERE I WOULD LIKE THE VARIABLE "COUNT" TO BE
REFRESHED EACH TIME ONE FORM WAS HIDDEN AND ANOTHER WAS DISPLAYED."-->
</div>

<div id="all_forms">

<form id="ques1">
<p>Question 1?</p>
<button onclick="calculate_priv(this.form.id, 1, 'no')">Add $1</button>

<button onclick="calculate_priv(this.form.id, -1, 'no')">Subtract
$1</button>
<button onclick="calculate_priv(this.form.id, 0, 'no')">Unsure-no
change</button>
</form>

<form id="ques2">
<p>Question 2?</p>
<button onclick="calculate_priv(this.form.id, 1, 'no')">Add $1</button>

<button onclick="calculate_priv(this.form.id, -1, 'no')">Subtract
$1</button>
<button onclick="calculate_priv(this.form.id, 0, 'no')">Unsure-no
change</button>
</form>

<form id="ques3">
<p>Question 3?</p>
<button onclick="calculate_priv(this.form.id, 1, 'yes')">Add
$1</button>
<button onclick="calculate_priv(this.form.id, -1, 'yes')">Subtract
$1</button>
<button onclick="calculate_priv(this.form.id, 0, 'yes')">Unsure-no
change</button>
</form>

</div>
</body>
</html>
 
C

Chris Lieb

[snip]
function write_currency()
{
//document.write("<div id='currency'>Balance in the Piggy Bank: $"
+count+ "</div>"); IF I TRY TO WRITE THE HTML HERE, IT OVERWRITES THE
FORM AND ONLY THE AMOUNT SHOWS.
document.getElementById("currency").style.display = "block";
} [snip]
<strong>Balance in the Piggy Bank: </strong>Needs to update with the
count variable<!--THIS IS WHERE I WOULD LIKE THE VARIABLE "COUNT" TO BE
REFRESHED EACH TIME ONE FORM WAS HIDDEN AND ANOTHER WAS DISPLAYED."-->
</div>
[snip]

document.write can only modify the document while it is being loaded
initially. If you try to call it after the document has finished
rendering, the document is replaced. Try

document.getElementById("currency").innerHTML = "Balance in the Piggy
Bank: $" + count;

This will work in IE, but doesn't seem to in Gecko-based browsers
(Firefox and Mozilla). For them, you will have to use DOM methods. If
you are only inserting text (no tags), then use this:

document.getElementById("currency").firstChild.data = "Balance in the
Piggy Bank: $" + count;

If you want to insert tags also, you will have to do a lot more with
the DOM, which I really don't have the expertese to go into. For it,
you'll have to wait for some of the regulars to come around.

HTH

Chris Lieb
 
R

RobG

Chris Lieb wrote:
[...]
document.write can only modify the document while it is being loaded
initially. If you try to call it after the document has finished
rendering, the document is replaced.

Your definition of 'modify' seems to exclude completely replace.

It might be splitting hairs, but document.write can modify the document
whenever it is called, but the effect of doing so after the document has
finished loading is as you say - it replaces the content completely.

document.getElementById("currency").innerHTML = "Balance in the Piggy
Bank: $" + count;

This will work in IE, but doesn't seem to in Gecko-based browsers
(Firefox and Mozilla).

Did you test that? innerHTML is very widely supported and it works for
me in both those browsers.

For them, you will have to use DOM methods. If

Not *have to*, but can. Use of DOM to modify document content is
recommended where table structure is involved or for more than trivial
insertion of text and one or two elements. For simple insertion of text
innerHTML is generally adequate.

you are only inserting text (no tags), then use this:

document.getElementById("currency").firstChild.data = "Balance in the
Piggy Bank: $" + count;

Did you test that? In the posted code, for Gecko browsers, the
firstChild of 'currency' is an empty text node caused by the white space
between the end of the opening 'div' tag and the start of the 'strong'
tag. IE removes the white space and doesn't insert the text node.

IE sees the firstChild as the 'strong' element, its first child is the
text node with "Balance in the... " as its content, so for IE you want:

...("currency").firstChild.firstChild.data = ...


In Gecko browsers (Firefox, Mozilla, et al) your code will add the text
to the first empty text node before the 'strong' element, essentially
prepending it to the existing content, not replacing it.

That is why attempting to identify a specific node using DOM tree
navigation should not generally be attempted, particularly going down
the tree (i.e. through descendants). Use getElementById() and grab the
element directly, or some other method to positively identify the node
you are after.

If you want to insert tags also, you will have to do a lot more with
the DOM, which I really don't have the expertese to go into.

The original div was something like:

<div id="currency">
<strong>Balance in the Piggy Bank: </strong></div>

To make life easier, add a SPAN element for the balance - it will have
no visible effect at all on the layout:

<div id="currency">
<strong>Balance in the Piggy Bank: <span
id='balance'></span></strong></div>


To modify the content text using DOM you could use:

// Test for support of required methods
if ( !document.getElementById ||
!document.createElement) {
return;
}

// Get a reference to the element
var el = document.getElementById('balance');

// Delete the current content if there is any
while (el.firstChild) {
el.removeChild(el.firstChild);
}

// Write the new content
el.appendChild(document.createTextNode(count));


That works in IE too, but innerHTML may be simpler.
 
A

Andrea

Thanks Rob and Chris for the suggestions and explanation of
document.write(). It's very helpful.
 
P

Patient Guy

Chris Lieb wrote:
[...]
document.write can only modify the document while it is being loaded
initially. If you try to call it after the document has finished
rendering, the document is replaced.

Your definition of 'modify' seems to exclude completely replace.

It might be splitting hairs, but document.write can modify the document
whenever it is called, but the effect of doing so after the document has
finished loading is as you say - it replaces the content completely.

document.getElementById("currency").innerHTML = "Balance in the Piggy
Bank: $" + count;

This will work in IE, but doesn't seem to in Gecko-based browsers
(Firefox and Mozilla).

Did you test that? innerHTML is very widely supported and it works for
me in both those browsers.


Here's the problem with the property 'innerHTML'. It does break in
earlier versions of NetNav and Mozilla, although these property-and-method
extensions of the "other major browser" developer may now be incorporated
in the script interpreter as fast as they are enunciated, and also
depending on whether any takes Microsoft seriously any longer in the
Javascript/JScript/ECMAscript war of script specifications.

I believe there are a class of script writers who is sticking to the
promulgations of the "Standards" organizations: ISO, W3C, ECMA. Or in
the case of the exceedingly humble and modest W3C, script writers are
sticking strictly to the "Recommendations" organizations (on the idea that
to assert "standards" for the organism that is the Internet is contrary to
the principle this organism is not be "chained" or "manacled" to things
like "standards").

At any rate, if 'innerHTML' is a specific extension of some browser
developer and not written in a universally respected specification, it
doesn't go in the code, with the warning that some day it just might break
in a future version when the interpretation of it is dropped.

Then there is the class of script writers who fill up their documents with
if-else code blocks that work with Browser #1, Browser #2, and Browser #3
when they won't operate with the common (dare we say standard?) code. (I
recommend this approach even though it invariably requires finding
getting-around-to-it time.)

I guess it just depends upon how adamant scripters want to be: follow
some org's standard, in which both the standard and the org as they are
now may not be around in 10 years, and assuming one actually believes
their script might hold up and be of use for that long....
 
T

Thomas 'PointedEars' Lahn

Patient said:
Here's the problem with the property 'innerHTML'. It does break in
earlier versions of NetNav and Mozilla,

AFAIK major `innerHTML' issues were fixed in Mozilla/5.0 rv:0.9.1.
Of course Mozilla/4.x, which was very much broken, and early Mozilla
milestones, which were hardly usable beside being test cases, never
upported innerHTML nor did they support the W3C DOM. Mozilla/4.x
supports document.layers which no other UA does. Your point being?
although these property-and-method extensions of the "other major browser"
developer

Probably you are talking about the AOM/DOM of these browsers as that is
what it is. Not the language was extended, the AOM/DOM was.
may now be incorporated in the script interpreter as fast as they are
enunciated,

It is not a language issue. Learn to understand the difference between
(interfacing) language and AOM/DOM.
and also depending on whether any takes Microsoft seriously any longer in
the Javascript/JScript/ECMAscript war of script specifications.

No, it is not. `innerHTML' is nowadays widely supported, not only by
Gecko-based and IE-based UAs. It is _not_ a Bad Thing to use it if it
is feature-tested before.
I believe there are a class of script writers who is sticking to the
promulgations of the "Standards" organizations: ISO, W3C, ECMA. Or in
the case of the exceedingly humble and modest W3C, script writers are
sticking strictly to the "Recommendations" organizations (on the idea that
to assert "standards" for the organism that is the Internet is contrary to
the principle this organism is not be "chained" or "manacled" to things
like "standards").

You have yet to understand what the ECMA and W3C are. FYI: They are not the
sole body bullying, and being completely independent of. companies in the
IT segment and other organizations that you present it to be. Read the
ECMA membership list, the W3C membership list and the list of contributors
to W3C specs.

Standardization and recommendations helps to create interoperable code.
They help to keep things running in a way all can benefit. For example,
we would not be discussing here if there were not an RFC on NNTP/UUCP.
At any rate, if 'innerHTML' is a specific extension of some browser
developer and not written in a universally respected specification, it
doesn't go in the code, with the warning that some day it just might break
in a future version when the interpretation of it is dropped.

That is at best shortsighted reasoning . There is no specification
whatsoever on what window.open() really does and that goes for many
AOM/DOM features that at some point in history (before JavaScript 1.5)
were considered part of of the language and now are no longer but are
still widely supported through the AOM/DOM of user agents. There is
nothing wrong in using proprietary DOM features if the resulting code
is not written in a way that entirely depends on them.
I guess it just depends upon how adamant scripters want to be: follow
some org's standard, in which both the standard and the org as they are
now may not be around in 10 years, and assuming one actually believes
their script might hold up and be of use for that long....

You missed the point completely. And in 10 years from now, it is highly
unlikely that any current script code will still work, let alone the
Internet and Web being what it is now.


PointedEars
 
P

Patient Guy

AFAIK major `innerHTML' issues were fixed in Mozilla/5.0 rv:0.9.1.
Of course Mozilla/4.x, which was very much broken, and early Mozilla
milestones, which were hardly usable beside being test cases, never
upported innerHTML nor did they support the W3C DOM. Mozilla/4.x
supports document.layers which no other UA does. Your point being?

In the text that followed, the point was made. It is that innerHTML and
layers are properties/methods/objects that adhere to no standard. It is
true that they often emerge in the absence of a
standard/specification/recommendation, and that the browser
developer/manufacturer hopes that their idea catches on.
Probably you are talking about the AOM/DOM of these browsers as that
is what it is. Not the language was extended, the AOM/DOM was.


It is not a language issue. Learn to understand the difference
between (interfacing) language and AOM/DOM.

I don't claim it is a language issue. The discussion here is about the
seeming hesitation of a script writer to make use of a property
('innerHTML') that is featured and available in all the browsers, despite
it being no part of a specification/standard/recommendation.

In using innerHTML, the script writer risks (at a higher probability than
something actually part of a standard) that the code will break in future
versions of a browser which strictly adhere to standards.
No, it is not. `innerHTML' is nowadays widely supported, not only by
Gecko-based and IE-based UAs. It is _not_ a Bad Thing to use it if it
is feature-tested before.

see my comment above.

Those who use non-standard code just because it works risk that the code
will not work if even the browsers that feature the object/property/method
decide not to later on.

You have yet to understand what the ECMA and W3C are. FYI: They are
not the sole body bullying, and being completely independent of.
companies in the IT segment and other organizations that you present
it to be. Read the ECMA membership list, the W3C membership list and
the list of contributors to W3C specs.

I wasn't making any attempt at all the describe the membership of these
organizations or their structure. I was only commenting on one function
they serve: to develop standards/specifications/recommendations which they
hope are universally adopted in the interest of making software developers
productive in making working code, and avoid a waste of time in writing
browser-dependent code. To some degree, more or less, they achieve that
goal.
Standardization and recommendations helps to create interoperable
code. They help to keep things running in a way all can benefit. For
example, we would not be discussing here if there were not an RFC on
NNTP/UUCP.

And I said something different from the purpose of what a standard or
recommendation is?
That is at best shortsighted reasoning . There is no specification
whatsoever on what window.open() really does and that goes for many
AOM/DOM features that at some point in history (before JavaScript 1.5)
were considered part of of the language and now are no longer but are
still widely supported through the AOM/DOM of user agents. There is
nothing wrong in using proprietary DOM features if the resulting code
is not written in a way that entirely depends on them.

If you had read the entirety of my text and actually not edited out
(apparently for the sole purpose of being needlessly argumentative!), you
will see that I make that very point that coding for browser-specific code
is something a script writer is recommended in doing.

I insert the text here that I wrote in the post you responded to, and which
you either did not read or did not understand:

Then there is the class of script writers who fill up their
documents with if-else code blocks that work with Browser #1,
Browser #2, and Browser #3 when they won't operate with the
common (dare we say standard?) code. (I recommend this approach
even though it invariably requires finding getting-around-to-it
time.)

If there are sentences in that paragraph that you did not understand,
please indicate which ones, and I will attempt to re-phrase.

You missed the point completely.

Exactly to what point are you referring?
And in 10 years from now, it is
highly unlikely that any current script code will still work, let
alone the Internet and Web being what it is now.

"...and assuming one actually believes their script might hold up and
be of use for that long..."

Is my English usage really that confusing? For how is that expression of
my doubt in the workability of scripts at a future time in that sentence
fragment really different from your assertion at the end here?
 
T

Thomas 'PointedEars' Lahn

Patient said:
In the text that followed, the point was made.

It was not.
It is that innerHTML and layers are properties/methods/objects that adhere
to no standard.
True.

It is true that they often emerge in the absence of a
standard/specification/recommendation, and that the browser
developer/manufacturer hopes that their idea catches on.

So? We are discussing _real-world_ implementations.
I don't claim it is a language issue.

Don't be ridiculous.
In using innerHTML, the script writer risks (at a higher probability than
something actually part of a standard) that the code will break in future
versions of a browser which strictly adhere to standards.

No, only in using innerHTML _un-feature-tested_.
see my comment above.

Which I cannot agree to. Browser scripting, or user agent scripting for
that matter, inevitably involves features that are not part of any
standard. There is no standard for `window' or `document', for example,
hence not even alert() and document.getElementById() etc. are per se
standards compliant. The host object referred to by `document' probably
implements parts of the Document or HTMLDocument interface, and that
interface provides a getElementById() method, but that is it. It is a Good
Thing to adhere to standards, but to make not adhering to them a no-no,
is ridiculous.
Those who use non-standard code just because it works risk that the code
will not work if even the browsers that feature the object/property/method
decide not to later on.

You obviously have far too less professional experience in client-side
scripting to set the standards (in terms of minimum requirements) other
people's work should be based on.
I wasn't making any attempt at all the describe the membership of these
organizations or their structure. I was only commenting on one function
they serve: to develop standards/specifications/recommendations which
they hope are universally adopted in the interest of making software
developers productive in making working code, and avoid a waste of time in
writing browser-dependent code. To some degree, more or less, they
achieve that goal.

True. However, you tried to belittle the status of standardization bodies
in general, the W3C and their specifications, by ignoring their members.
And I said something different from the purpose of what a standard or
recommendation is?

You debated that Internet standards were viable in the first place:

(see above)
| [...] script writers are sticking strictly to the "Recommendations"
| organizations (on the idea that to assert "standards" for the organism
| that is the Internet is contrary to the principle this organism is not
| be "chained" or "manacled" to things like "standards"

Not considering that this a appeal-to-motive logical fallacy (you cannot
know why the W3C decided to call their specifications "Recommendation" and
you cannot know why your "script writers" decided to follow them), Internet
standards _are_ _definitely_ viable or both of us would not be here now.

And not only <URL:http://www.w3.org/Consortium/> makes it clear that W3C
Recommendations should be considered Web standards. Since the Web is a
part of the Internet, that would make them Internet standards. You have
understood the difference between Web and Internet, have you not?
If you had read the entirety of my text

I have. Perhaps you should also have before submitting it.
and actually not edited out

I have not edited out anything important to your argumentation. If I did,
it was because it was easy to miss the red thread in it, if there was any.
See below.
(apparently for the sole purpose of being needlessly argumentative!),

If you you cannot face arguments against your arguments, this is the wrong
place for you.
you will see that I make that very point that coding for browser-specific
code is something a script writer is recommended in doing.

No, you made and make the point that what is not standardized should
therefore not be used at all. Which is wrong, especially in terms of
Web browser scripting.
I insert the text here that I wrote in the post you responded to, and
which you either did not read or did not understand:

Then there is the class of script writers who fill up their
documents with if-else code blocks that work with Browser #1,
Browser #2, and Browser #3 when they won't operate with the
common (dare we say standard?) code. (I recommend this approach
even though it invariably requires finding getting-around-to-it
time.)

So? You point out that your very argument contains a contradiction.
But perhaps you were not argumenting at all.
[...]
And in 10 years from now, it is highly unlikely that any current script
code will still work, let alone the Internet and Web being what it is
now.

"...and assuming one actually believes their script might hold up
and be of use for that long..."

Again a contradiction in your argument. You argue for standards because
they are long-living (they /are/ longer living than proprietary approaches,
that's for sure), but you argue also that any script may not be usable in
the future. If you want to argue for or against something, you better
decide what are you arguing for or against.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top