473,656 Members | 2,793 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamically adding to a div

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?

--
Thank You.

Michelle
Aug 25 '05 #1
9 39761
You can create tags and add them dynamically. This is probably better
than appending to innerHTML.

Here is a working sample that will get you started:

<html>
<head>
<script type="text/javascript">

function addStuff() {

var i = document.create Element( 'input' );
i.type = 'text';

var d = document.getEle mentById( 'mydiv' );
d.appendChild( i );
}
</script>

</head>
<body>
<div id="mydiv">
</div>
<button onclick="addStu ff()">Add Stuff</button>
</body>
</html>

Brian Pearson.

Aug 25 '05 #2
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.create Element('input' );
oInp.type = 'text';
oInp.value = 'More blahdy blah blah';
document.getEle mentById('xx'). appendChild(oIn p);
">

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
Aug 25 '05 #3
I just tried this and works great. I will have to wait until tomorrow and
try it at work. At work I am actually adding table elements containing text
boxes, radio buttons, etc. I am using the table related tags for
positioning the elements. I am trying to create the table elements but
without success. Here I was trying the createTextNode but of course I did
not get the desired result.

function addData() {

var i = document.create Element( 'input' );
i.type = 'text';
var theDiv = document.getEle mentById("aDiv" );

var existingHtml;
existingHtml = '<table><tr><td ><input type="text"
name="address"/></td></tr></table>';
var j = document.create TextNode(existi ngHtml);

theDiv.appendCh ild( j );
}

Can I use the createElement for creating a table and the necessary <tr> and
<td> tags? I want something like this to be added to the div:

<table>
<tr>
<td><input type=text name=address></td>
</tr>
</table>


--
Thank You.

Michelle
"bwpearso" <br***********@ gmail.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
You can create tags and add them dynamically. This is probably better
than appending to innerHTML.

Here is a working sample that will get you started:

<html>
<head>
<script type="text/javascript">

function addStuff() {

var i = document.create Element( 'input' );
i.type = 'text';

var d = document.getEle mentById( 'mydiv' );
d.appendChild( i );
}
</script>

</head>
<body>
<div id="mydiv">
</div>
<button onclick="addStu ff()">Add Stuff</button>
</body>
</html>

Brian Pearson.

Aug 25 '05 #4
This is what I came up with for creating the table in the div:

function addData() {

var i = document.create Element( 'input' );
i.type = 'text';
var theDiv = document.getEle mentById("aDiv" );

var existingHtml;
existingHtml = '<table><tr><td ><input type="text"
name="address"/></td></tr></table>';
var j = document.create TextNode(existi ngHtml);

var table = document.create Element( 'table' );
var tableBody = document.create Element('tbody' );
var newrow = document.create Element("tr");
var newcol = document.create Element("td");

newcol.appendCh ild(i);
newrow.appendCh ild(newcol);
tableBody.appen dChild(newrow);
table.appendChi ld(tableBody);

theDiv.appendCh ild( table );
}

--
Thank You.

Michelle
"Michelle" <md*****@mindsp ring.com> wrote in message
news:IvaPe.1738 2$g47.4452@trnd dc07...
I just tried this and works great. I will have to wait until tomorrow and
try it at work. At work I am actually adding table elements containing
text boxes, radio buttons, etc. I am using the table related tags for
positioning the elements. I am trying to create the table elements but
without success. Here I was trying the createTextNode but of course I did
not get the desired result.

function addData() {

var i = document.create Element( 'input' );
i.type = 'text';
var theDiv = document.getEle mentById("aDiv" );

var existingHtml;
existingHtml = '<table><tr><td ><input type="text"
name="address"/></td></tr></table>';
var j = document.create TextNode(existi ngHtml);

theDiv.appendCh ild( j );
}

Can I use the createElement for creating a table and the necessary <tr>
and <td> tags? I want something like this to be added to the div:

<table>
<tr>
<td><input type=text name=address></td>
</tr>
</table>


--
Thank You.

Michelle
"bwpearso" <br***********@ gmail.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
You can create tags and add them dynamically. This is probably better
than appending to innerHTML.

Here is a working sample that will get you started:

<html>
<head>
<script type="text/javascript">

function addStuff() {

var i = document.create Element( 'input' );
i.type = 'text';

var d = document.getEle mentById( 'mydiv' );
d.appendChild( i );
}
</script>

</head>
<body>
<div id="mydiv">
</div>
<button onclick="addStu ff()">Add Stuff</button>
</body>
</html>

Brian Pearson.


Aug 25 '05 #5
Michelle wrote:
I just tried this and works great. I will have to wait until tomorrow and
try it at work. At work I am actually adding table elements containing text
boxes, radio buttons, etc. I am using the table related tags for
positioning the elements. I am trying to create the table elements but
without success. Here I was trying the createTextNode but of course I did
not get the desired result.

function addData() {

var i = document.create Element( 'input' );
i.type = 'text';
var theDiv = document.getEle mentById("aDiv" );

var existingHtml;
existingHtml = '<table><tr><td ><input type="text"
name="address"/></td></tr></table>';
var j = document.create TextNode(existi ngHtml);
That will create a text node that has the content of 'existingHTML' as
a string, it will not be parsed and rendered as if it were HTML or you'd
used innerHTML.

theDiv.appendCh ild( j );
}

Can I use the createElement for creating a table and the necessary <tr> and
<td> tags? I want something like this to be added to the div:
You can use DOM methods to create any HTML elements, there is a brief
(though a bit old) tutorial here:

<URL:http://www.oreillynet. com/pub/a/javascript/synd/2001/08/17/DOM-2.html>

The Mozilla DOM reference is reasonable:

<URL:http://www.mozilla.org/docs/dom/domref/>

The table interface is here;

<URL:http://www.mozilla.org/docs/dom/domref/dom_html_ref12. html#998953>

<table>
<tr>
<td><input type=text name=address></td>
</tr>
</table>


The equivalent using DOM is:

function addData() {

if ( ! document.getEle mentById ||
! document.create Element ) {
// getElementById or createElement are not supported
// handle error - substitute other methods or
return;
}

var theDiv = document.getEle mentById("aDiv" );

if ( ! theDiv ) {
// couldn't find the div, handle error
return;
}

var oTable = document.create Element('table' );
var oTb = document.create Element('tbody' );
var oTr = document.create Element('tr');
var oTd = document.create Element('td');
var oIp = document.create Element('input' );
oIp.type = 'text';
oIp.name = 'address';

oTd.appendChild (oIp);
oTr.appendChild (oTd);
oTb.appendChild (oTr);
oTable.appendCh ild(oTb);
theDiv.appendCh ild(oTable);
}

The code could be reduced a little by using the insertRow method (the
tbody would not have to be created & added).

However, using a table for the above is not really suitable - you should
be using a div and CSS to do the layout. An alternative is to clone an
existing element, modify its attributes and add it.

You might also consider having all required elements in the page and use
script to hide/show them rather than creating them.
--
Rob
Aug 25 '05 #6
Thanks Rob. You have been most helpful!!

--
Thank You.

Michelle
"RobG" <rg***@iinet.ne t.au> wrote in message
news:Ma******** ********@news.o ptus.net.au...
Michelle wrote:
I just tried this and works great. I will have to wait until tomorrow
and try it at work. At work I am actually adding table elements
containing text boxes, radio buttons, etc. I am using the table related
tags for positioning the elements. I am trying to create the table
elements but without success. Here I was trying the createTextNode but
of course I did not get the desired result.

function addData() {

var i = document.create Element( 'input' );
i.type = 'text';
var theDiv = document.getEle mentById("aDiv" );

var existingHtml;
existingHtml = '<table><tr><td ><input type="text"
name="address"/></td></tr></table>';
var j = document.create TextNode(existi ngHtml);


That will create a text node that has the content of 'existingHTML' as a
string, it will not be parsed and rendered as if it were HTML or you'd
used innerHTML.

theDiv.appendCh ild( j );
}

Can I use the createElement for creating a table and the necessary <tr>
and <td> tags? I want something like this to be added to the div:


You can use DOM methods to create any HTML elements, there is a brief
(though a bit old) tutorial here:

<URL:http://www.oreillynet. com/pub/a/javascript/synd/2001/08/17/DOM-2.html>

The Mozilla DOM reference is reasonable:

<URL:http://www.mozilla.org/docs/dom/domref/>

The table interface is here;

<URL:http://www.mozilla.org/docs/dom/domref/dom_html_ref12. html#998953>

<table>
<tr>
<td><input type=text name=address></td>
</tr>
</table>


The equivalent using DOM is:

function addData() {

if ( ! document.getEle mentById ||
! document.create Element ) {
// getElementById or createElement are not supported
// handle error - substitute other methods or
return;
}

var theDiv = document.getEle mentById("aDiv" );

if ( ! theDiv ) {
// couldn't find the div, handle error
return;
}

var oTable = document.create Element('table' );
var oTb = document.create Element('tbody' );
var oTr = document.create Element('tr');
var oTd = document.create Element('td');
var oIp = document.create Element('input' );
oIp.type = 'text';
oIp.name = 'address';

oTd.appendChild (oIp);
oTr.appendChild (oTd);
oTb.appendChild (oTr);
oTable.appendCh ild(oTb);
theDiv.appendCh ild(oTable);
}

The code could be reduced a little by using the insertRow method (the
tbody would not have to be created & added).

However, using a table for the above is not really suitable - you should
be using a div and CSS to do the layout. An alternative is to clone an
existing element, modify its attributes and add it.

You might also consider having all required elements in the page and use
script to hide/show them rather than creating them.
--
Rob

Aug 25 '05 #7
ASM
bwpearso wrote:
You can create tags and add them dynamically. This is probably better
than appending to innerHTML.

Here is a working sample that will get you started:

<html>
<head>
<script type="text/javascript">

function addStuff() {

var i = document.create Element( 'input' );
i.type = 'text';
something.type stops the function with my IE Mac
seems this IE has a bug (one more !)
it type is not set : all run correctly
(a kind of textbox is displayed)

var d = document.getEle mentById( 'mydiv' );
d.appendChild( i );
}
</script>

</head>
<body>
<div id="mydiv">
</div>
<button onclick="addStu ff()">Add Stuff</button>
</body>
</html>

Brian Pearson.

--
Stephane Moriaux et son [moins] vieux Mac
Aug 25 '05 #8
ASM
RobG wrote:
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 );
"> 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.create Element('input' );
oInp.type = 'text';
oInp.value = 'More blahdy blah blah';
document.getEle mentById('xx'). appendChild(oIn p);
">

Now if you look at the inner HTML, Firefox does not show the value
attribute of the new input,


Did I mistake ?

because new inputs are set in div 'xx'
if I press [See innerHTML]
FF(*) alert displays all html inside this div
(with attributes as 1st made)

of course, changes in values are not more rendered by [See innerHTML]

are these changes what you want to say by :
"Firefox does not show the value attribute of the new input"
(*) all my browsers except IE do the same as FF

--
Stephane Moriaux et son [moins] vieux Mac
Aug 25 '05 #9
ASM
Michelle wrote:
I just tried this and works great. I will have to wait until tomorrow and
try it at work. At work I am actually adding table elements containing text
boxes, radio buttons, etc. I am using the table related tags for
positioning the elements. I am trying to create the table elements but
without success. Here I was trying the createTextNode but of course I did
not get the desired result.


Do your add ons are allways the same ?

If yes

- display a table of one (or more?) rows styled in none
- clone this table as soon as you need to add inputs
- appendChild this clone and style it to block (or table? to verify)

on my idea, it's the simplier way to do

adding a row to a table example :
(was for different color betwen rows 1 and 2)
(in french, enter a number in 1st input then press [GO]
<http://perso.wanadoo.f r/stephane.moriau x/internet/web_dom/clones/test_clones_css _dom.shtml>
which doesn't work correctly with my IE

--
Stephane Moriaux et son [moins] vieux Mac
Aug 25 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1717
by: Aaron Ackerman | last post by:
I have a bound combobox the appears on a cell within the column of my bound grid when the user clicks on a cell n(In my vb.net WinForm app). I am trying to allow the adding of an item to that bound combo by allowing the user to dynamically type in the new value directly in the combo box whcih in turn updates the lookup table and then when they have finished leaves that particular cell on the grid with the correct value. Seems...
11
2286
by: Steven D'Aprano | last post by:
Suppose I create a class with some methods: py> class C: .... def spam(self, x): .... print "spam " * x .... def ham(self, x): .... print "ham * %s" % x .... py> C().spam(3) spam spam spam
0
1718
by: Sinisa Ruzin | last post by:
Hi all, I had problem with dynamically adding/removing controls;ascx, Controls.Add(Page.LoadControl... in the same page of the IBuySpy portal. ASP.NET, C#. I added buttons to the main ASCX loaded by desktopdefault.aspx. The buttons were used to "navigate" withing the same page. I had the problem with "fail to load viewstate ...." due to a mismatch controls in the treeview in the viewstate. Dynamically removing controls was messy and it...
3
2185
by: Byron Hopp | last post by:
Anybody have code to add a ToolBar, and its buttons to a MDI Child window. I have added the Toolbar, and added the buttons, but how do you determine what the button is going to execute upon the user clicking it. How do you add this code dynamically? Byron...
3
2191
by: Ben Dewey | last post by:
Okay, so I have a base Page class called ArticlesPageBase. This base class has reads in an overridable ArticleId and Loads the data into a Panel object in the ContentPlaceHolder of the Master. The article that it loads from the Database is a xml field that contains html code for the article. I added some custom html to the database article called <question id="22" /> When the article contains inline questions are parse out the start...
5
12575
by: J | last post by:
I am having problems dynamically adding more than one event handler to an input. I have tried the Javascript included at the bottom. The lines inp.attachEvent('onkeyup', makeEventFunc1(strand)); inp.attachEvent('onchange', makeEventFunc2(strand)); individually work in IE, but when used together, only the bottom one remains active. I have also tried
5
3202
by: Liquidtouch | last post by:
I'm not much of a HTML or Javascript programmer but have a little experience just hacking away at it. I am creating a HTML application and would like to be able to add or remove rows of a table. The row that gets added will need to contain 2 columns, 1 which contains an IFRAME, and the other will contain a Javascript Menu which will be used to select the content displayed in the IFRAME. The purpose of the tool is to be used as a video...
2
1368
by: ganesh22 | last post by:
Hi, the below code is for dynamically adding textbox, but it will adding for same textbox only my requirement is how many times i click add button such times textbox will add for ex: if i click 10 times add button 10 textboxs will add Session = "3"; for (int a = 0; a < int.Parse(Session.ToString()); a++) { TableRow tr = new TableRow(); TableCell tc = new TableCell();
4
4474
by: Lewis Holmes | last post by:
Hi I have the following situation in one of my asp.net pages. The user can add multiple table rows to a form by selecting a button. These rows can contain asp.net controls. When this button is selected, the row is added using JavaScript. The script uses cloneNode to clone a hidden template row and all of its children and then adds the new row to the table, updates all of the child control Ids and sets visibility etc. The hidden...
1
34126
by: vivek kapile | last post by:
Title:Dynamically adding table row with a checkbox using JavaScript Author:Vivek Kapile Email:snipped Language:JavaScript Platform:JavaScript in ASP.net Technology:Used in ASP.net Level:Beginner Introduction
0
8382
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8498
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7311
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5629
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1930
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1600
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.