Michelle wrote:
I have a div that is initially empty. Clicking on a button will add some
text boxes and other controls so the user can add additional records. In
IE
all works fine but in Netscape 7.0 when I add another "record" the values
for all previous controls within the div are wiped out. In the javascript
function where I add on to the html in the div if I capture all the data in
the previous "records" then after adding the new record I can repopulate
all
the previous controls. I add to the div by getting the innerHTML. Is this
the best way to do this or is there another way to preserve the data?
Is it the 'best' way? Depends, but it seems not.
innerHTML is a good quick 'n dirty way of modifying a document but as
there is no public standard for what it should do or how it should
behave, different implementations vary from Microsoft's implementation
in ways that you may only discover when you push the bounds of what it
can do.
innerHTML is good for writing text content for an element, even with a
bit of formatting, but going beyond that you may start to have problems.
innerHTML does not always reflect the dynamic changes that have been
made to a document - e.g. attached events or modified styles. This
stuff is quite inconsistent across browsers as you have just discovered.
For example, consider the following text input:
<div id="xx">
<input type="text" value="blah">
</div>
<input type="button" value="See innerHTML" onclick="
alert(document.getElementById('xx').innerHTML);
">
If you look at the innerHTML using IE, the content of the value
attribute will be whatever is actually in the input. In Firefox, the
content of the value attribute will always be 'blah' (i.e. what is in
the HTML source), regardless of changes the user may have made.
A more robust way to modify a document is by using the document object
model (DOM), which is based on open standards so you more consistent
support (but as always there are browser-specific quirks and foibles).
Add the following button to after the button above - it adds a new text
input:
<input type="button" value="Add an input" onclick="
var oInp = document.createElement('input');
oInp.type = 'text';
oInp.value = 'More blahdy blah blah';
document.getElementById('xx').appendChild(oInp);
">
Now if you look at the inner HTML, Firefox does not show the value
attribute of the new input, IE does (normally the code would be in a
separate, general function but this is just a demo).
innerHTML should never be used to modify a table, though it can be used
to write an entire table or modify the contents of a cell (TD element).
If you are adding form controls or such, then DOM is a much better solution.
If you post an example of what you are trying to do, you will likely get
some help with how to do your innerHTML stuff with DOM.
--
Rob