You are on page 1of 90

Encoding html using javascript's escape & unescape

There are a couple of reasons that you may want to encode some (or all) of your source
html, these include:

• Slightly increased security - by protecting your source from being easily read you are
making it more difficult for anyone trying to find a workaround to your site (includes
spoofing payments and gaining access to members areas)
• Protection for automated non-javascript enabled crawlers - many of these are used
to harvest email addresses from websites to add to spam mailing lists, and encoded
email address will not be recognised as they cannot process the javascript.

There is also a downside however. Users of your website may well be veiwing it on a non-
javascript enabled browser or have javascript turned off (usually done to avoid malicious
scripts and auto-popups), if the site user is unable to process the javascript then they too
will be unable to read the information that has been encoded and it will appear missing from
the page.

Enter the text to encode here:

Encoded html:
<script type="text/javascript">document.write(unescape("

"));</script>

How it's done

It's encoded by using the escape() function and then further special characters are encoded
using the following routine:
function encodeMyHtml() {
encodedHtml = escape(encodeHtml.htmlToEncode.value);
encodedHtml = encodedHtml.replace(/\//g,"%2F");
encodedHtml = encodedHtml.replace(/\?/g,"%3F");
encodedHtml = encodedHtml.replace(/=/g,"%3D");
encodedHtml = encodedHtml.replace(/&/g,"%26");
encodedHtml = encodedHtml.replace(/@/g,"%40");
encodeHtml.htmlEncoded.value = encodedHtml;
}
It is then dispayed by utilising the unescape() fuction which will turn it all back into html:
<script type="text/javascript">document.write(unescape(" my encoded html "));</script>
./with Imagination
A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

• Articles
• Screencasts
• Podcasts
• Dailies
• Prototypes
• About
• Archives
• Contrast
• Tour

• A
• A+
• A++

Add and Remove HTML elements dynamically with


Javascript
Monday, February 28th, 2005

UPDATE: There is a newer “up-to-date” version of this entry posted on January


02, 2008. View Add and Remove Elements with JavaScript (reprise).

I’m going to tell you straight up front. I hate Javascript. I hate it because it owns me. Today, it
owned me. But within a few hours, I reversed the curse (In my past life I was a song writer).

In the following article, I’m going to show you how you can dynamically create HTML elements
with content wrapped within them according to the DOM2 specification. Why would this be
useful? Just take one look at the add/remove HTML element demo.

Those who have a GMail account probably recognize its similarity to the attachment feature
when composing new email. Since Gmail’s javascript seems to be hidden… or scrambled… or…
whatever they did to it, I was left in the dark trying to figure this one out on my own.
Read on to see some explanation of this garbagio that had me tearing my hair out. Lastly, just as
a heads up, it may be better than you read the rest of this article using the Undesigned style sheet
so that you may have better readability of the code.(Only available on old site design)

First of all, the (x)html is real simple.

xHTML Snippet
<input type="hidden" value="0" id="theValue" />
<p><a href="javascript:;" onclick="addElement();">Add Some Elements</a></p>
<div id="myDiv"> </div>

The hidden input element simply gives you a chance to dynamically call a number you could
start with. This, for instance could be set with PHP or ASP. The onclick event handler is used to
call the function. Lastly, the div element is set and ready to receive some children appended unto
itself (gosh that sounds wierd).

Mkay, so far so easy. Now the JS functions.

addElement JavaScript Function


function addElement() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = 'Element Number '+num+' has been added! <a href=\'#\'
onclick=\'removeElement('+divIdName+')\'>Remove the div "'+divIdName+'"</a>';
ni.appendChild(newdiv);
}

removeElement JavaScript Function


function removeElement(divNum) {
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}

The addElement function sets a variable by grabbing the element of which we will append a
child node to. So in this case, we use the classic getElementById method to track it down. We of
course supply the empty ‘myDiv’.

The next three lines basically grab the value of the hidden input element and give your function a
starting number to begin with. Then each time the function is called, your value is incremented.
This is important for when you need to remove elements, since you’ll need unique id’s.
You’ll notice next the createElement is used to… well… make a new div element. But wait, it
needs an id. Thus, we use the setAttribute method to append an id and a value to it. At this
point, we have the uniquely named divIdName and we will plug that into the equation for our
newdiv object.

Now you’re ready for some content garbagio to put inside your dynamic div element using the
innerHTML property. And this is when it gets fun. Within your HTML supplied in the
innerHTML of the dynamically created div element, you need to provide a link to remove itself.
Afterall, that’s the point of this whole thing, right? It wouldn’t be flexible if all we could do is
only add and not remove.

So, a link is put inside with an event handler that calls the function removeElement. Great.
Simple enough. Let’s move onto that function.

Okay, now that is easy. First off, it grabs the same parent div element by using getElementById
and stores it in a variable. We then get the element to which we passed in as an argument to the
function (which was created from the addEvent function), and we store that in another variable.
Then voila! We remove like so:

d.removeChild(olddiv);

Play with it, study it, tell your Uncle about it. This may not seem like a big deal, but it has
potential to do some really cool stuff.

283 Responses to “Add and Remove HTML elements dynamically with


Javascript”

1. Justin Perkins

March 9th, 2005 at 12:58 am

Ahh, DOM. I love it so much. Glad you’re finding that Javascript is not all evil.

Adding a DIV is not really an event though, watch what you call your functions as they
should make sense to other people not familiar with your code.

2. Justin Perkins

March 9th, 2005 at 1:02 am

Maybe I should qualify that a little bit…

An event is something like a hover, click, keypress, load, etc. An “event handler” is
activated when the event occurs.

This would be a typical “addEvent” function in Javascript:


function addEvent(obj,evType,fn,useCapture){
var ret=false;
if(obj!=null){
if(obj.addEventListener){
obj.addEventListener(evType,fn,useCapture);
ret=true;
}
else if(obj.attachEvent){
obj.attachEvent(”on”+evType,fn);ret=true;
}
}
return ret;
}

3. Dustin

March 26th, 2005 at 10:54 pm

just to be clear on what I was doing Justin, I was pulling this from a “Track & Field” add
Event module. Event in this case stands for the Athletes Event such as high jump, pole
vault or the mile.

I know exactly what the differences are ;)

4. Chris

June 1st, 2005 at 12:12 am

Good article. Just what I was looking for!

5. Dave Greiner

August 8th, 2005 at 1:13 am

Awesome tips, thanks so much Dustin. This will come in super handy for an upcoming
app I’m working on.

6. Samuel

August 17th, 2005 at 7:53 am

Excelente Sr. Diaz. Muchas gracias.

7. Chris Peters

August 18th, 2005 at 12:06 pm


Consider your code raped and pasted. Thank you for helping out with this great article. :)

8. Dustin Diaz

August 18th, 2005 at 1:02 pm

I’m glad you’re making sweet love to it.

9. Loic Deniel

August 18th, 2005 at 11:42 pm

Thanks again for this Dustin, this is really cool

10.Dustin Diaz

August 19th, 2005 at 9:26 am

Just a heads up. I took some of Justin’s advice and renamed the original functions to
addElement and removeElement just so that one doesn’t get confused with Scott
Andrew’s famous addEvent function.

11.Chris Peters

August 20th, 2005 at 12:19 am

Not only will I be making sweet love to it. But all of the workers for Franklin County,
Ohio, will be making sweet love to it on their Intranet.

12.cro

August 24th, 2005 at 7:15 pm

this is just what i was looking for… but i became greedy. any chance to build up an entire
page this way? say, write a .js to spawn the whole thing or something like that? seems to
work on anything inside a page, but i can’t figure out how to start one from scratch.
thanks anyway

13.Dustin Diaz

August 24th, 2005 at 10:46 pm

The Demo shows how to create sample content. And although it’s not W3C DOM
methods (since it uses innerHTML) it’s pretty widely supported and there are plenty of
folks requesting that it becomes a standards. I mean really, it’s so easy to use.

So for your purpose, I suppose, you could try just setting up separate blocks of code you
want to insert as html, and call them out upon clicking on different options etc.
So yea, in short: You can create an entire page from scratch given the right tools. That is
the pretty much the entire idea of a WYSIWYG Editor.

14.Elio Todaro

September 8th, 2005 at 12:44 pm

I don’t have a reply but a question.

I need to remove an html input control which was not created dinamically.

I tried removeChild but it didn’t work.


Any suggestion will be appreciated.

15.Dustin Diaz

September 8th, 2005 at 1:12 pm

Elio,
A typical way to delete an element since there is no removeElement DOM method, you
need to grab a reference of the element, find it’s parent, then remove the element
reference.

eg.
var el = document.getElementById('abc');
el.parentNode.removeChild(el);

16.Elio Todaro

September 9th, 2005 at 6:29 am

Thanks for your help Dustin,


now everything works.

17.Sreeni.A

September 19th, 2005 at 4:53 am

Hi freinds ,
In a html page I am creating a row with three form elements ( 2 text boxes and one select
box) dynamically just by pressing a button. But now how can I code it to remove the row
which is created lately?

Can anybody help me please?

Sreeni.A

18.Dustin Diaz
September 19th, 2005 at 10:37 am

remember to target your elements with an object finder like getElementById or


getElementsByTagName. If you have <input id=”test” type=”text” /> and you want to
remove it… you simply invoke a function that does the following:

function rem() {
var t = document.getElementById(’test’);
t.parentNode.removeChild(t);
}

You can invoke the function with any event you like. The most simple and obvious is a
click event. For instance, have a link fire off a function like the one I just wrote.

Hope that helps.

19.Amol M Vaidya

September 20th, 2005 at 5:04 am

Thats a really cool article, simple and sweet. A thousand thanks for that

20.John

September 20th, 2005 at 4:27 pm

How would you do this for a form? For example, I want to give a user the option to
upload multiple files. Do I add the newly created elements to the form?

21.Dustin Diaz

September 20th, 2005 at 4:42 pm

John,
Funny you mention that. This post was originally inspired from that problem. My idea
was to create something similar to the gmail uploader to attach files.

Easy enough, name your input elements with an array like <input type=”file”
name=”files[]” /> and you can catch them in php by counting the array length. Thus,
when you’re creating new element, just do it as so:

function makeInput() {
var input = document.createElement(’input’);
input.type = ‘file’;
input.name = ‘files[]‘;
}
Make sense?

22.John

September 20th, 2005 at 5:00 pm

Thanks, makes sense, but don’t you lose the ‘removeElement’ functionality?

23.Christina

September 24th, 2005 at 4:15 am

This is lovely. I’m climbing up the steep side of the DOM learning curve; and it’s a huge
help to find explanations and examples.

Would anyone else around here feel like showing any working examples of this, so we
can join all the workers in Franklin County, Ohio?

24.John

September 24th, 2005 at 1:49 pm

I figured out how to attach it to my form and everything works just like I want it. Thanks
, this will work well in the application I’m building. :)

25.Slim Shady

October 2nd, 2005 at 2:34 pm

> Dustin said:


> just to be clear on what I was doing
> Justin, I was pulling this from a
> “Track & Field” add Event module. Event
> in this case stands for the Athletes Event
> such as high jump, pole vault or the mile.

> I know exactly what the differences are

very helpful article

(even if dustin’s a little sensitive about his coding skills ;) )

26.Hannes Baldursson

October 18th, 2005 at 10:02 am

Regarding upload forms, I have a much cleaner method. Stickmans blog


Pretty neat idea. I do it diffrently, and it’s currently not working :-p

You can see my version, and problem on free2code.com forums

27.Tom

October 19th, 2005 at 9:47 am

Hi, very nice example.


I tried it online and it was ok, but when I copy
the source code, and try it on my machine it doesn’t work. It was not possible to remove
the items.
Is it possible that in the code , I have to write a pagename instead the javascript?
And which page?

28.Tom

October 19th, 2005 at 9:53 am

Sorry, to my question forward. We code I mean is:

29.GeniX

October 22nd, 2005 at 1:15 am

Great example, i’m gonna steal it, thx!

30.Chris

October 22nd, 2005 at 2:32 pm

Just wanted to say thanks for a great howto! This was exactly what I was looking for. I’m
no javascript expert, but I was able to modify the code to work nicely with some form
fields.

31.ShorTTy

November 8th, 2005 at 6:04 pm

I have been scouring the ‘net and Googling for aaages for a decent AJAX tutorial that
does exactly this… I HAVE FOUND THE HOLY GRAIL. =)

Thank you so much, my life is now complete. Off I go, getting my head around this new
technology.

This is the best site ever.


32.Dustin Diaz

November 8th, 2005 at 6:10 pm

ShorTTy,
Your life will soon begin. I’m glad I could tell about just a few of the basics since -in
fact- these are the details most sites leave out. I hate that, don’t you?

33.mynameis

November 10th, 2005 at 9:31 pm

This was helpful to me ..but not fully….


I’m adding a set of elements(which contains 2 text areas and radio button.) the radio
button when clicked will open up text box.
Now I am able to get these new appended sets. But the appended sets show js error when
I click the radio button and doesn’t show the text box.
Pls reply asap

34.Dave L

November 11th, 2005 at 5:14 pm

Nicely done! I had nearly given up searching when I found your tutorial. I adapted your
technique to work with file type input boxes too.

Sincerely,

David Levin

35.Yong Chen

November 16th, 2005 at 6:16 pm

Dear Dustin,

I am working on a project which needs a functionality of selecting multiple file at a time


on the client side for uploading several files to the server.

I found the following code snippet somewhere, but i encountered the error
“mFile.children.valueis null ” when using it. Could you please help me.

function mCreateFile(obj){
var eF
var mName
mFileName.innerHTML=”"
if (obj.id==”File”) {
for (i=0;i”+mName[mName.length-1]+”"
}
}
mstatus.innerHTML=”总共有 “+(mFile.children.length-1)+” ‰¸ªæ–‡‰»¶ç-
‰å¾…‰¸Š‰¼ ”
}

if (obj.id==”File_New”) {
eF=document.createElement(”)
mFile.appendChild(eF)
obj.id=”File”
}
}

table{
FILTER:
progid:DXImageTransform.Microsoft.Shadow(direction=135,color=#999999,strength=3)
;
}
input{
border:1px soild #000000;
font-family:Verdana,Arial,宋‰½“;
font-size:12px;
padding:2px;
}
#mTD{
LINE-HEIGHT: 24px;
}
#mFile{
width:203px;
float:left;
|
#mFileName{
float:right;
width:182px;
}
#NameDetail{
overflow:hidden;
width:176px;
color:#000000;
font-family:Verdana,Arial,宋‰½“;
font-size:12px;
cursor:default;
height:22px;
}
#mstatus{
font-size:12px;
color:#ff0000;
}

æ·»åŠ éª„‰»¶

总共有 0 ‰¸ªæ–‡‰»¶ç‰å¾…‰¸Š‰¼

36.ScorpRash

November 21st, 2005 at 4:32 am

Dear Dustin,

In my project I am having a html button control generated dynamically through .NET c#


language. I have added attributes and associated javascript function to that control. Till
that its fine.
Now my requirement is based on some input from user I need to dynamically APPEND
or REMOVE the javascript event hanlder to that control.
Say, If for button “onClick” i have “func1();” and “func2();” associated, I may need to
remove “func1();
dynamically and add “func3();” to the same “onclick” event. I wish to accomplish this
using javascript. Is it possible? If so, can you please advice.
Note: The control and its id are also known only at runtime (i.e., When we go for Page
view source).

37.Priya

November 21st, 2005 at 6:21 am

Here’s an offshoot - I need to add a form element dynamically to my HTML - would I use
a concept similar to above? Great article by the way!

38.Sanket

November 21st, 2005 at 12:23 pm

Hi there,

This article is really GREAT !! I was searching for this, since last year. And after about an
year, Ultimately I got it. My thanks to the creator of Script

Sanket

39.shipra

November 30th, 2005 at 1:03 am


Hi,
Nice article.It has solved one of my problem,Thanks .
There is another problem iam facing.Like in Gmail, how do upload the file?
Where and how to call the auto save for attach file?

If you could help please do reply.


Thanks a lot

40.Peter

December 7th, 2005 at 2:20 pm

Hey Dustin, thanks for the code snippets, looking to incorporate them into a coming
project but I’m having trouble and thought you might be able to help. I need to
dynamically create not 1, but 12 inputs, and 1 text area. So, they press a button, 12 text
fields and 1 area. Press it again? 12 more inputs and 1 area, etc. Ive tweaked your code to
be able to dynamically generate all the fields I need, complete with names, values and
type definitions…however…its..ugly. I need to format it, wrap it inside (hate to say this
cause im a css standards guy…) a table and thats where everything breaks. Append
merely chucks it at the bottom of the DIV, I need to be able to control where it goes, and
to format it by appending it right inside a specific TD. Is this possible? I tried
innerHTML but that defeats the purpose of the DOM2 compliant code, and didnt
necessarily work either. Not even sure you’ll get this, but thanks nonetheless for some
great code. Cheers-

41.Dustin Diaz

December 7th, 2005 at 2:41 pm

Hey Peter. The innerHTML dillemma is one that I refuse to tackle right now. It’s fully
supported even on ie5.x browsers so I’ve yet to find a good reason not to use it. Sure it’s
not in the standard DOM2 specs, but it’s even getting more highly adopted as it is now
effective in Firefox 1.5 for XML which only shows that it’s more likely to get adopted
sooner or later by the W3C.

Another thing you can do is put a generic ‘div’ element in the spot you wish to put your
dynamicly created content, then use appendChild or innerHTML in that spot.

Also, make sure your html string is all on one line in JavaScript. That will break your
code.

42.Alexandru

December 15th, 2005 at 10:53 am

Hy! I tried to get files from a php script and it wasn’t the name of the file ! it was the
name of the temp file! $file[0] will return the temp file copied to server temp folder!
43.Jeff

December 15th, 2005 at 5:16 pm

Hi,
I’ve been reading your site for some time. First, thanks for all the work and help!!! I’m
just getting into javascript and DOM so I hope you can bear with me. I have succesfully
used the script for my own purposes but now I am trying to add a set dynamic radio
buttons that when clicked show or hide a corresponding div with additional form info.
There are three divs and three radio buttons, I’ve tried using several different methods I
was able to find but the usual error I get is that the function is not defined. I’ve tried
everything I can to get it ot work without success. Is there something obvious I’m
missing here? I’m dying to figure this out now for peace of mind more than anything
else? I greatly appreciate your insite.

44.Ajay

December 21st, 2005 at 11:53 pm

hi,i have two buttons called accept and reject

and inside the body of my html,i have one div tag as follows

Response ;

when the user clicks on accept i want to replace

Response ;

as

Response ; accept

if the user clicks reject i need to make this as

Response ; reject

any luck

45.mdani

December 29th, 2005 at 9:53 am

Halo Dustin
i have checked the following script but i had error on remove function
and set for the better one:
this is from your site
function removeElement(divNum) {
var d = document.getElementById(’myDiv’);
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}

this is from me:

function removeElement(divNum) {
var d = document.getElementById(’myDiv’);
d.removeChild(divNum);
}

tested on IE6 and FireFox 1.0.7

CMIIW :)

46.Dennis

December 31st, 2005 at 9:33 pm

Great Code. I am having a problem that I cannot figure out. I am using ASP.NET 2.0. I
want to make a Usercontrol that uses this code, but when I post the data using the
ASP.NET button the added controls are not seen and I cannot figure out how to access
them. After the postback and the page is rerended to my browsder all the added controls
are gone.

Any ideas on what I am doing wrong and how to work arround this issue?

All code below:

Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs)


For Each oControl As Control In Controls

Stop

Next
End Sub

var email_count=0;

function remove_email(emailid) {
var d = document.getElementById(’emailtable’);
var olddiv = document.getElementById(’e’ + emailid);
d.removeChild(olddiv);
}
function add_email() {
email_count++;
var html=’Type’
html+=’HomeBusiness’
html+=’Required’
html+=’Address’
html+=’Required’
html+=”;

document.getElementById(”emailtable”).innerHTML += html;
}

Test Page

47.Dennis

December 31st, 2005 at 9:35 pm

Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As


System.EventArgs)
For Each oControl As Control In Controls

Stop

Next
End Sub

var email_count=0;

function remove_email(emailid) {
var d = document.getElementById('emailtable');
var olddiv = document.getElementById('e' + emailid);
d.removeChild(olddiv);
}

function add_email() {
email_count++;
var html='Type'
html+='HomeBusiness'
html+='Required'
html+='Address'
html+='Required'
html+='';

document.getElementById("emailtable").innerHTML += html;
}

function div_delete() {
//document.getElementById("div1").innerHTML.delete;// = "";
}
Untitled Page

48.Sraan

January 5th, 2006 at 10:04 am

Hi,

i was searching for adding an event to a dynamically created element and got to your
website.

Is there any way to add a event dynamically(ex:onClick=”openWin(xxxxx,xxx);”) to the


dynamically created element?

I am trying to get it work and no luck so far.

thanks
Sravan

49.Sraan

January 5th, 2006 at 1:38 pm

Hi,

finally i got it to work. But for some reason it just works in Netscape. It won’t fire
onclick event in IE when i click the “Add” button for created row. Any ideas??

Here is the code..

function addRow()
{
//get the table body for which to add a row
var tbody = document.getElementById(’table1′).getElementsByTagName (”tbody”)[0];
var lastRow = tbody.rows.length;
var iteration = lastRow + 1;//get the last row of the table and one for new row
//var tbody = document.getElementById(”table1″).getElementsByTagName(”tbody”)[1];
//get the tbody element
var row = document.createElement(”TR”);
var cell9 = document.createElement(”TD”);

cell9.style.textAlign = ‘center’;
cell9.className = “tbltan”;
var inp9 = document.createElement(”INPUT”);
inp9.setAttribute(”type”,”button”);
inp9.setAttribute(”name”,”bal_by_source” + iteration);
inp9.setAttribute(”value”,”Add”);
inp9.setAttribute(”size”,”10″);
inp9.setAttribute(’onClick’,”openWind(’xxx.cfm’,” + iteration + “);”);
cell9.appendChild(inp9);

row.appendChild(cell9);
tbody.appendChild(row);
}

50.Sean Hudson

January 5th, 2006 at 10:43 pm

Dustin,

First off, thanks for the article. I *think* I am starting to get the basics down, and articles
like this really help. I learn well by example.

However, I do have one problem. I cannot get the removeElement to work properly. I
copied the example directly from your page, but it no workie.

Thanks,
Sean

51.Cid

January 6th, 2006 at 3:46 am

It’s a great code but how can I customize the div?

I’d like to position it and put it above the other HTML content.How can that be achieved?

Thanks

52.Scott Martin

January 6th, 2006 at 9:22 am

Just though I would say great example and with only a little tweaking got it to add new ’s
and remove them then let me add the same line agian.
Image map selection for selecting different areas and adding them to their list, then
removing them, then adding them agian, etc..
Thanks agian.

53.Guest

January 8th, 2006 at 8:15 pm


Thumbs up!

I modified the script to show INPUT field instead of plain text after clicking “add”…
newdiv.innerHTML = "";
…but in Firefox (v1.5), after sending the entire FORM with these generated INPUT
fields, none of them are passed nor recognized by REQUEST.FORM.
In IE works fine. Help appreciated.

Thanks!

54.Clint

January 11th, 2006 at 10:43 am

Yea, I’m having the same thing happen to me. PHP just does not seem to “see” the form
elements that I add via my addElement function… Anyone?

55.Chandra

January 13th, 2006 at 1:19 pm

Dustin
Two pleasures in one - what a sweet copncept. I think I’m re-growing all the hair I lost
trying to git-r-done with dynamic HTML and CSS.
Cool abd concise.

56.Adm.Wiggin

January 15th, 2006 at 8:39 pm

Dustin: Thank you. Wonderful article. Used this stuff for some of the admin end of the
Timpanogos Tribune. Beautiful.

57.BBlackmoor

January 15th, 2006 at 10:20 pm

This is a great tip. You saved me a lot of time figuring this out. Thanks.

58.New2Arrays

January 30th, 2006 at 8:31 pm

Great stuff! Very helpful. Can you show me how you write this using an Array so that I
could do things like add up the Array values? My goal is to be able to take the
dynamically created values and total some of them. Thank you.

59.Pete
January 31st, 2006 at 4:05 pm

Clint, this is from the Gecko DOM reference. I think it explains your dilemma.

Note that when you append to the innerHTML of a document, you have essentially
created a new document. The session history for the browser is incremented, and when
you go Back, the document is there in its original, unappended state.

I am in the initial stages of reseraching this– maybe if you don’t use innerHTML it would
work.

60.Dave Irvine

February 2nd, 2006 at 7:59 am

Hi,

i was searching for adding an event to a dynamically created element and got to your
website.

Is there any way to add a event dynamically(ex:onClick=”openWin(xxxxx,xxx);”)


to the dynamically created element?

I am trying to get it work and no luck so far.

thanks Sravan

Sraven, I’m having exactly the same problem. It works fine in netscape, firefox, but IE
refuses to pick up on the fact i’ve clicked on an element I’ve just added that has a new
onclick event… I’m doing something with dynamic ratings for articles, code as follows:

objectToAppend = document.createElement("img");
objectToAppend.setAttribute("src","images/starfilled.gif");
objectToAppend.setAttribute("onclick","javascript:rate(" + starnum +
"," + articleid + ");");
objectToAppend.setAttribute("id","article" + articleid + "ratingstar" +
starnum);
d.appendChild(objectToAppend);

Any ideas from anyone on how to get this working in IE?

61.Dave Irvine

February 2nd, 2006 at 8:53 am

Ok, so I answered my own question. The answer was in fact, in the example provided on
this page… innerHTML!
objectToAppend = document.createElement("div");
objectToAppend.setAttribute("id","article" + articleid + "ratingstar" +
starnum);
objectToAppend.setAttribute("class","rateimg");
objectToAppend.innerHTML = "&lt img src=\"images/starfilled.gif\"
class=\"rateimg\"
onclick=\"javascript:rate("+starnum+","+articleid+")\">";
d.appendChild(objectToAppend);

62.Crammit

February 16th, 2006 at 6:11 am

Hey ppl, have any of yous had any problems with either removeNode() and
removeChild() in regards to crashing IE… for me when ever any of these functions are
called IE quits unexpectedly with an error in mshtml.dll… Ive tried this on different
computers however all seem to have the same problem… I found a MS hotfix for this
however diddnt fix the problem :/ If anyone knows how to get around this Please Advise,
Thanks.

63.Qamar

February 17th, 2006 at 4:32 am

Hi
I need to implement css class to the input element button i created using Inner HTML.
Any help will be appreciated
thx
Qamar

64.Dave

February 21st, 2006 at 3:46 am

Hey Dustin great example, works nice and easily implemented to a drag and droppable
div to create dynamic workflow,

thanks for the ideas

65.John The Backpatter

February 24th, 2006 at 12:31 am

*pat*pat*pat*pat*pat*pat*pat*pat*pat*pat*

Exactly what i was looking for , THOUGH…


I’m actually taking a select from one iframe and recreating it in sister-frame, with minor
alterations, this will do. THANKS!
*pat*pat*pat*pat*pat*pat*pat*pat*pat*pat*

66.Jesse

February 26th, 2006 at 3:01 am

Really cool example, but a quick question:


Instead of adding a new div element, is there any way to simple populate an existing one?
Basically, what I’m trying to do is generate an empty table, then go back and populate it
dynamically from a database (sounds crazy, but trust me, there’s a reason for it). Any
ideas?
thanks!

67.Jesse

February 26th, 2006 at 3:15 am

never mind, I figured it out. I was just blind, and didn’t see it, very simple example:

testing set image value

function addtext(){ document.getElementById(’testArea’).innerHTML = “Blah!”; }

68.Guest

March 3rd, 2006 at 12:39 pm

Sraan,

I have not tested this solution with your code, but a similar problem I had with IE and
trying to use an attachEvent() call was solved by using “onclick” instead of “onClick.”
Apparently IE is case-sensitive.

69.SHISHIR RAJ ADHIKARI

March 10th, 2006 at 2:04 am

Good one.Thanks for it.I was looking for it very badly.

70.suchitra

March 10th, 2006 at 2:55 am

Hi,
After adding element dynamically some rows, then how can i edit those rows.

It’s cool code..

suchitra

71.Laurence

March 13th, 2006 at 6:07 pm

Hi, is there any way to dynamically create a media player with the source depending on
the result of a query string passed to it from the previous page with the coded link? I am
able to pass the query between pages ok, but haven’t figured out how to pass the result to
the source attribute of an embedded media player.

Any help is appreciated. Cheers.

72.dane

March 17th, 2006 at 3:07 am

Hey love your tut :) Thank God for people like you..

Ive noticed a bit of typo in newdiv.innerHTML .. you might want to check it..

73.Tom

March 20th, 2006 at 11:39 am

If you want a good place to go for AJAX examples and tutorials, try
http://ajaxpatterns.org.

74.Tony

March 22nd, 2006 at 1:37 pm

ShorTTy mentioned that he had been “Googling for aaages for a decent AJAX tutorial
that does exactly this”, I feel obligated to point out that this is NOT AJAX. There is
nothing AJAX about this functionality. Ajax is Asynchronous JavaScript And XML, by
the very basic nature it’s suppose to interact to a server; this example here does no such
thing. It merely changes client side and has no interaction with a server.

http://en.wikipedia.org/wiki/AJAX

75.Dave

March 24th, 2006 at 9:21 am


PLEASE HELP!! I can not implment the code to work.

“+”"+”"+”"+”";
var newTR = document.createElement(’TR’);
newTR.innerHTML = textString;
ni.appendChild(newTR);
}

// –>

Add Milestone

I have additional rows with the same td already i want to add more.

I have been pulling my hair out doing this!

76.audienceone

March 30th, 2006 at 8:09 am

Is there a full working code for this one. I mean a sample implementation using a form
and form validation as well.

77.Vani Bandargal

March 30th, 2006 at 11:25 am

Any body knows how to access dynamicaccly added html elements in Javascript?
First I add some input text elements on client side on click of “Add Row” buton which is
working fine.
Now I need to validate the value entered in those new form fields before submitting the
form.

78.Jon

April 5th, 2006 at 6:43 am

Thanks for the script. I need to dynamically add some plain text and some text areas like:

Label 1: Textbox1
Label 2: Textbox2

How can I do that? The script let me add textbox and seems like they are all on the same
line. Any help will be appreciated.

79.Simon
April 6th, 2006 at 3:47 am

Hi,
I’ve used your script in my web application and it works a treat in IE, but when i use the
script in FF it still adds the correct content but as the screen grows vertically downwards
the elements i am adding render over the top of the containg table. in IE the containg
table is steched to fit in the extra content, Any body else had a problem like this

80.Kris Randall

April 7th, 2006 at 5:13 pm

Hi Dustin,
Your probably sick of hearing it by now but you have done a fantastic job with this
example.
Thanks so much.

81.Solie

April 9th, 2006 at 9:12 pm

Hello,
I’m trying to add textfields dynamically to a form. innerHTML is read only. So is their a
way to add a form element dynamically?

Thanks

Solie

82.jithendar

April 12th, 2006 at 12:46 am

A big Thank you to Dustin! from another javascript hater ;-)

I’ve implemented dynamic Text Box’s using your code,Could you give me a few pointers
as to how i could grab the value of each Text Box

thank you
jithendar

83.Kiril Cvetkov

April 13th, 2006 at 10:39 am

hey Dustin,
Thank you so much for that code. it helped me a lot.
At first place I was having some problems with it, but with few switches on commas at
the ‘innerHTML’. it is working perfectly now.
and I changed the remove code a little bit.
here is what I did:

function addElement() {
var ni = document.getElementById(’myDiv’);
var numi = document.getElementById(’theValue’);
var num = (document.getElementById(’theValue’).value -1)+ 2;
numi.value = num;
var newdiv = document.createElement(’div’);
var divIdName = ‘my’+num+’Div’;
newdiv.setAttribute(’id’,divIdName);
newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! Remove the div
“‘+divIdName+’”‘;
ni.appendChild(newdiv);
}
function removeElement(divNum) {
var d = document.getElementById(’myDiv’);
d.removeChild(divNum);
}

I’m programing in php, I don’t know does it matter.


Thanks again.

best regards,
kiril

84.Kiril Cvetkov

April 13th, 2006 at 10:43 am

I’ll post it again ’cause it’s not seen very good at my last post. I’ll replace the “”
characters with “*”
newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! *input
name=”field’+num+’” type=”text” value=”" /**a href=”#”
onclick=”removeElement(’+divIdName+’)”>Remove the div “‘+divIdName+’”*/a*’;

thanks again

85.gagan

April 14th, 2006 at 6:50 am

me so horny at this piece o code….


i like it a laaaaaaaaat
thanks !!

86.feanor

April 14th, 2006 at 1:27 pm

i’m trying to do something similar but i’m creating a textarea dynamically and trying to
get at what the user typed in it in my vbscript… so far i had no luck here, the code

function input(obj){

var radioName = obj.getAttribute(”name”);


var hiddenName = ‘txt’ + radioName;
var hidden =document.getElementById(hiddenName);
var newText = document.createElement(’textarea’);
newText.setAttribute(”id”, “textbox”);
hidden.parentNode.appendChild(newText);

}
what i’m trying to do is insert a textarea next to the hidden input. the function is called
when a radio button is clicked. so far so good, i see the textarea. now, in my vbscript i
want the text in the textarea, but it seems there is no way for me to access it. here’s what i
tried…

any ideas?

87.Dan

April 17th, 2006 at 6:42 am

The code is wonderful, thank you so much. The only road block i’ve ran into is addind
floating (float:left) div’s in a container.

If the static divs are 90 pixels high (not set, just end up that high) and then i use
addElement() to add a new div with an img tag in the innerHTML, the new DIV’s are
only as high as the previous.

This isn’t an issue in IE, only FIREFOX. I also have a function that adjusts the height of
every DIV after the addElement has done it’s thing, but still no luck.

Any ideas?

88.shridhar

April 19th, 2006 at 4:13 am


on click radio button we get text box using java script

89.mike

April 20th, 2006 at 5:42 am

Hey all,

This is great.

One issue for me is though I am creating the element, in FF (my best friend) the append
ignores WHERE the div is in the code and displays it at the TOP of the page no matter
what.

This is obviously a major issue as you want the content to be displayed where ever you
wish.

Has anyone had this issue, can anyone help?

ex:

… code …

… code …

but displays as:

… code …

90.John

April 20th, 2006 at 4:53 pm

Thanks a bunch for the tutorial. Great stuff!

91.Vetra

April 30th, 2006 at 12:53 pm

Nice article, very helpful and it works :)

92.Ashley

May 9th, 2006 at 9:23 am

Instead of using a div element, I would like to use . I’m also wanting to dynamically add
a user control into the column.
How would I go about doing this?

Any help is much appreciated! Thanks :)

93.Ashley

May 9th, 2006 at 9:24 am

sorry, I would like to dynamically create a new row and column.

94.Celsol

May 12th, 2006 at 8:01 am

Great script, been looking for something like this for a few days now, big thank you to
Dustin Diaz for sharing knowledge..

95.Chris

May 12th, 2006 at 5:15 pm

Hey guys,

I am using this technique to clear html file input controls. As all might know, file input
controls do not allow that the value attribute is cleared (for security reasons) so I do this
by deleting the current input control and create a new one identical to the previous (when
a clear button is clicked). Everything works fine, but the only thing that bugs me is that
the newly created input control is not being displayed with its assigned class attribute
(css), therefore not looking like the other one. Is there a reason for this? I would
appreciate a lot your help.

Thanks in advance!

96.sreejith

May 18th, 2006 at 2:37 am

very good

97.Akshay

May 18th, 2006 at 10:17 pm

Many thanks to you. I am new to programming and I was yesterday gvn this task to
add/remove bunch of controls by client-side scripting. It was wonderful. The way gvn
abv worked quite well.
Thanks again.
Best regards
-Akki

98.Justin Hambleton

May 22nd, 2006 at 2:38 pm

Anyone know how I would re-index the added elements? For example, each new element
increases the index by 1, however when I remove an element, it doesn’t refresh the index.
For example: I add four elements (Item #1, Item #2, Item #3, Item #4). I decide to delete
Item #2, leaving Item #1, Item #3 and Item #4. I would like Item #4 to become Item #3
and Item #3 to become Item #2. Hopefully this makes sense.

99.Chadwick

May 25th, 2006 at 7:35 am

function removeElement(divNum) {
var d = document.getElementById(’myDiv’);
d.removeChild(divNum);
}

100.Chadwick

May 25th, 2006 at 7:36 am

oops on the last post…. I can’t get the remove function to work in FF. Works just fine in
ie but I get a “my1Div is not defined” error via the javascript console…

function removeElement(divNum) {
var d = document.getElementById(’myDiv’);
d.removeChild(divNum);
}

101.Chadwick

May 25th, 2006 at 11:37 am

Well I figured it out. In ie when calling the removeElement() function, single quotes
aren’t required. In ff they are. So when I created my innerHTML I just had to make sure
that my divIdName was in quotes like so…

… onclick=”removeDriver(\”+divIdName+’\');” />
I also reworked the addElement() function to provide a little less code.

function addCar()
{
var ni = document.getElementById(’myDiv’);
var numi = document.getElementById(’theValue’);
var num = Number(numi.value);
numi.value = ++num;

var newdiv = document.createElement(’div’);


var divIdName = ‘myDiv’+num;
newdiv.setAttribute(”id”,divIdName);

newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! Remove the div
“‘+divIdName+’”‘;
ni.appendChild(newdiv);
}

102.Gareth Stirling

May 26th, 2006 at 6:00 am

Is there a way to use the code in a drop down menu?

103.Xavier

May 27th, 2006 at 11:05 pm

Hey Gareth Stirling !!

Here is the code for select object:

selElement = document.createElement(’select’);
selElement.setAttribute(’name’, ‘field_name’);
var o = document.createElement(”OPTION”);
var t = document.createTextNode(”Select Options”);
o.setAttribute(”value”,”0″);
o.appendChild(t);
selElement.appendChild(o);

104.Mark

May 30th, 2006 at 4:28 pm

————————
Hi,

i was searching for adding an event to a dynamically created element and got to your
website.
Is there any way to add a event dynamically(ex:onClick=”openWin(xxxxx,xxx);”)
to the dynamically created element?

I am trying to get it work and no luck so far.

thanks Sravan

Sraven, I‪m having exactly the same problem. It works fine in netscape, firefox, but
IE refuses to pick up on the fact i‪ve clicked on an element I‪ve just added that
has a new onclick event… I‪m doing something with dynamic ratings for articles,
code as follows:

objectToAppend = document.createElement(”img”);
objectToAppend.setAttribute(”src”,”images/starfilled.gif”);
objectToAppend.setAttribute(”onclick”,”javascript:rate(” + starnum + “,” + articleid +
“);”);
objectToAppend.setAttribute(”id”,”article” + articleid + “ratingstar” + starnum);
d.appendChild(objectToAppend);

Any ideas from anyone on how to get this working in IE?

———————-

Hi, everyone:

I was having a similar problem as the code above. Here’s what I did to get it to work in
both IE and Firefox. I changed the line:

objectToAppend.setAttribute(”onclick”,”javascript:rate(” + starnum + “,” + articleid +


“);”);

to:

objectToAppend.onclick = function() {rate(starnum, articleid);};

Hope this helps anyone who finds this (It drove me nuts for over a day :) )

Mark

105.Ed

May 31st, 2006 at 9:16 am

Thanks for the great tutorial, and thanks to Chadwick for the quote solution!

106.Joseph Szymbabwe
May 31st, 2006 at 4:08 pm

Hey, I have this div on my site put there dynamically by my free hosting provider. Is
there a way to remove using derrivitives from this script? I tried to find it but I’m not that
‘Fluent’ in DOM and Javascript. The script that the free hosting provider puts is located
at http://gig4free.com/freesites/include.js. The DIV i’m trying to delete is called
“divStayBottomLeft” (subtle isn’t it :-) ). Thanks for your enormous help!

107.Raman Basu

June 17th, 2006 at 9:17 am

It sounds good to manipulate HTML element using javascript, but what about
dynamically generated dropdowns which are nested and dependent ????

Any Idea?

108.Oliver Jackson

June 19th, 2006 at 6:46 am

Joseph (106)

what about something like this

function noDivBottomLeft() {
var noStay = document.getElementById(’divStayBottomLeft’);
noStay.parentNode.removeChild(noStay);
}

then use a

109.Oliver Jackson

June 19th, 2006 at 6:48 am

… continued

use a onload=”noDivBottomLeft()” in body tag

110.Ceejay

June 30th, 2006 at 1:04 am

Cool !!!

Using it to clean up dynamically created AJAX “windows” when closing them.


Keep them comming.

111.Adriaan

July 2nd, 2006 at 5:28 am

Very cool script! Thanks alot!

112.Adriaan

July 2nd, 2006 at 8:01 am

I’m using the script to create 2 html select inputs, which works great btw, I get an error
however when trying to get the POSTed values in Firefox. They are received 100% in IE,
but nothing that was created dynamically is POSTed through in Firefox.

Does anybody have any idea why?

Please help!

Thanks

113.Sujit

July 5th, 2006 at 5:01 am

Thanks a lot for it. hope its gng to work for me.

114.Kim Steinhaug

July 6th, 2006 at 9:33 am

Hmm, sems alot of users are having problems with Firefox and dynamically added
elements. Seems that when you submit the form added elements are not included in the
submit. Needless to say I am having the exact same problem, and only in Firefox. It has
nothing to do with this example, however googling landed me here so I share my agony
as noone has answered the problem yet.

I am also adding the elements with innerHTML, maby I need to create the elements more
correctly with the DOM - maby that will work. I will post my findings.

115.Kim Steinhaug

July 6th, 2006 at 9:42 am


Hmm, I know did a test with adding all new fields correctly with the DOM and
createElement() method. Same problem, Firefox doesnt recognize the dynamically added
fields. Looks like I’m going for a “doesnt work with Firefox” sollution… hmm…

116.Kim Steinhaug

July 6th, 2006 at 9:48 am

Alrighty, the sollution is at hand. Seems that a blast from the past gave me this problem.
In the old days before CSS we usually defined a form like this to avoid troublesome
padding and margins :

This is not validating looking at the nesting of the elements, so if we do it correctly like
this :

Firefox will work, naturally it works anyways in IE because of the nice error handling we
sometimes loose our heads over…

117.Kim Steinhaug

July 6th, 2006 at 9:49 am

OK, seems the parser chopped away the code, lets do some pseudo code again :

table
form
tr
td

/td
/tr
/form
/table

This doesnt work, this does :

form
table
tr
td

/td
/tr
/table
/form

118.Amrita

July 11th, 2006 at 3:05 am

Hi,
I am looking for code to add a drop down box dynamically to a particular position and
not to the end of the form….
i have used the following javascript code:

var newsel= document.createElement(’select’);

newsel.setAttribute(’id’,newSelect);
var emptyOption=document.createElement(”option”);
emptyOption.setAttribute(”value”,”");
emptyOption.innerHTML=”Hi i’m a new box”;
newsel.appendChild(emptyOption);

form.appendChild(newsel);

the above code works fine,but appends the dropdown to the end of the form (as i’ve used
form.appendChild) but the dropdown box isnt even displayed if i dont use
form.appendChild
could anyone help….

thanx in advance…

119.shyam

July 12th, 2006 at 11:01 pm

this is just what i was looking for… Very cool script! Thanks alot. big thank you to
Dustin Diaz for sharing knowledge..

120.Ali

July 14th, 2006 at 8:45 am

Thank’s, it’s a great article.

121.Upratovanie

July 19th, 2006 at 8:36 pm


Hi people,
it’s 5:30 am. I’m just having a cup of coffee and I just came across this excellent and
useful article. I must say to you, Dustin: Good job!

I was searching for some JS-based function which allow me to add new objects. And this
article resolved this my problem! Thanks, Dustin.

122.Yukti

July 19th, 2006 at 11:34 pm

hi
even i have problem with FIREFOX not posting the values well.A solution could be
creation of an array in javascript , with index of the array as controll name and the values
be the one added by the user.Setting the array to the hidden field and checking on the next
page after POSt. Hope this works .. sooon will come with the code

regards
Yukti

123.Jeswin

July 20th, 2006 at 10:59 am

i used your code to add an additional table (form) when a button is clicked. i have many
textboxes in it, i need to append value/id to each textbox when it gets created, so that
each textbox has a unique id.. i passed the value

let me know if this will create a unique id each time when the table gets created?

124.Tbroas

July 22nd, 2006 at 9:15 am

Great code, thanks for providing it. I have question. I am using it to dynamically create
input (text) fields so that users can add rows to a table and then type text into the field. I
can get this to work fine:

function addEvent()
{
var ni = document.getElementById(’myDiv’);
var numi = document.getElementById(’theValue’);
num = (document.getElementById(”theValue”).value -1)+ 2;
numi.value = num;
num = num - deleted;
var divIdName = “my”+num+”Div”;
var step =”step”+num;
var newdiv = document.createElement(’div’);
newdiv.setAttribute(”id”,divIdName);
newdiv.innerHTML = “Step: “+num+” “;
var x = “Step: “+num+” “;
alert(x);
newdiv.innerHTML +=” “;
ni.appendChild(newdiv);
}

I want to be able to set the value of these new input fields, but I can’t seem to get it to
work. I can get it to work on text input fields that are not created with “createElement”,
but for some reason I can’t get it to work on input fields created with the code provided.
Any ideas why? Is there a way to append the the new input field?

125.Chris

July 27th, 2006 at 8:16 am

This helps me out greatly. This is very much appreciated.

126.CraigM

July 30th, 2006 at 7:09 pm

Yukti - don’t worry about the hidden controls.

Look at what Kim said above. She nailed it. I was having this problem too and as she did
I had the “old school” habit of nesting my form elements inside my TABLE elements to
prevent extra padding, which is a no-no and Firefox does not like it.

Make sure your page elements are nested properly


(FORM,TABLE,TR,TD,/TD,/TR,/TABLE,/FORM) and I think you will find it works
great!

As for the evil padding, I believe there is a way to set this using CSS these days - I will
look for this next.

127.tulasi

July 31st, 2006 at 4:52 am

Very thanks to Mark for giving the code that


how to add event dynamically to dynamically added control

128.Adriaan

July 31st, 2006 at 1:34 pm


Everybody that gets the problem with firefox NOT receiving the POSTed values of the
dynamically created inputs. It is because your tag is within a or another similar tag. Put
your form tags right on the outside and it will work!

Hope this helps you!

129.Adriaan

July 31st, 2006 at 1:35 pm

Everybody that gets the problem with firefox NOT receiving the POSTed values of the
dynamically created inputs. It is because your form tag is within a table or another similar
tag. Put your form tags right on the outside and it will work!

Hope this helps you!

Sorry for the double post, but my tags was removed in the first post.

130.mike

August 3rd, 2006 at 10:36 pm

This is a great tool. I want to use it with a drag n drop sript I have. the script needs to
know what the name of new id’s are as they are created. for some reason when I inter
my1Div, my2Div…… the drag n drop script isn’t recognizing those ids. Any ideas. am i
getting the new ids right?

131.Jon

August 4th, 2006 at 8:51 am

i’m having the same problem as Chadwick with the “my1Div is not defined” error. i
changed it to single quotes but i still get the same error. This is what i have:

newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! Remove the div
‘+divIdName+’‘

the page adds ok, but it won’t remove them. any help would be appreciated! thanks!

132.Jon

August 4th, 2006 at 8:54 am

newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! href=”javascript:;”


onclick=”removeElement(’+divIdName+’);”>Remove the div ‘+divIdName+’/a’

hopefully now the code can be viewed, i took out the link tag
133.Jacob

August 4th, 2006 at 11:29 pm

Hi Mark,
Thanks a lot for sharing the knowlege on dynamically adding and removing html
elements.Hope you will continue the same

134.Bjarne

August 6th, 2006 at 10:25 am

Nice article… just what I was looking for.

A note thou: You dont need a hidden div!

document.body.appendChild(newDiv);

Will add you new div directly to the body of your document. I especially use it with
position:absolute, where I move my div’s around.

135.Monkey

August 9th, 2006 at 7:28 pm

Nice to see people using this stuff, thanks for the code Dustin.

small suggestion :
How about just passing the element or the element’s id to the function to remove, then
use the .parentElement property instead of trying to work out the specific container for
each item.

function RemoveScheduleItem( item )


{
item.parentElement.removeChild(item) ;
}

or use getElementById() if you can only pass in the id rather than the element itself.

Is this valid ? seems to work but then i only have to support MSIE for my current project.

Mike

136.Tom Bender

August 20th, 2006 at 9:26 am


I’m a server-side guy just recently biting the bullet on Javascript. Ughhhh

Your article came in particularily handy for my upcoming demo at Siemans AG.

Muchas Gracias!

137.Graham B

August 24th, 2006 at 8:53 am

Mike,

I’ve always used the parentElement.removeChild trick and it works perfectly across
browsers. Much neater than storing ids/references in variables.

138.Sven

August 25th, 2006 at 3:02 am

Hi,

Great article, this really is what I was looking for.

But I’m stuck with a question.


Why wouldn’t you use a global var instead of a hidden inputfield to count die id’s?

139.Paresh Prajapati

September 1st, 2006 at 2:05 am

Really very very usefull….


It really contain good help for managing dynamic html controls with javascript.

GREAT.

140.Anu

September 1st, 2006 at 2:41 am

Hai,

i want to make a button’s visible property false by using a javascript function.i mean i
want to create a javascript function in .aspx file. in that function i want to write code to
make a button’s visible property false and i want to call this function in another button’s
onclick event from .aspx file itself.how can i do?
please give me a reply?????????….
Anu

141.Margus

September 2nd, 2006 at 7:05 am

I would use CSS, to declare invisable state, and call it with JS:

.n‰htamatu { visibility:hidden }

Hide the button, with a Click on ME.

142.Margus

September 2nd, 2006 at 7:09 am

would use CSS, to declare invisable state, and call it with JS:
[code]

.nähtamatu { visibility:hidden }

Hide the button, with a Click on ME.

[/code]

143.Margus

September 2nd, 2006 at 7:15 am

I would use CSS, to declare invisable state, and call it with JS:

<script language=”javascript”><!–
function peida(id){document.getElementById(id).className=’nähtamatu’}//–>
</script>

<STYLE>
.nähtamatu { visibility:hidden }
</STYLE>

<P onclick= peida(’n')>


Hide the button, with a Click on ME.
</P>

<input type=”button” value=”Nupp” id=”N”>

DMN CODE BANNER


144.Raghavendra U

September 7th, 2006 at 1:27 am

Awesome, i can’t tell in words how simple it was how it helped me a lot, Thanks a Lot
Sir Thanks a Lot :
:-)

145.matthew

September 10th, 2006 at 6:48 pm

is there a way i could get the divs content from an external file, with the external file it
uses is called from the link that calls the creation of the div?.

146.Mr. Gundu

September 15th, 2006 at 11:53 am

Hi. I’m using this code to display a list of input from a user. Problem is that it adds the
new input below the old stuff so it looks like this:
Old
Old
New
What I would like for it to do though is add to it like this:
Old Old New
Any help would be great appreciated. Thanks for the starting point with this code Dustin.
It was fantastic to find it.

147.Heidi

September 18th, 2006 at 12:19 am

is it possible to remove only the elements in a div

148.Nick Marinho

September 19th, 2006 at 10:16 pm

This don’t work here, FIrefox 1.5, Opera and too not work in IE6.

This is my code:

function makeFile() {
var ni = document.getElementById(’divTexts’);
var numi = document.getElementById(’theValue’);
var num = (document.getElementById(’theValue’).value -1)+ 2;
numi.value = num;
var newdiv = document.createElement(’div’);
var divIdName = ‘file_’+num+’_';
newdiv.setAttribute(’id’,divIdName);
newdiv.innerHTML = ‘Nome: Email: ‘+divIdName+’‘;
ni.appendChild(newdiv);
}

function makeInput() {
var inp = document.getElementById(’divFiles’);
var numi = document.getElementById(’theValue’);
var num = (document.getElementById(’theValue’).value -1)+ 2;
numi.value = num;
var inpname = ‘text_’+num+’_';
var newinput = document.createElement(’input’);
newinput.setAttribute(’type’,'file’);
newinput.setAttribute(’id’,inpname);
newinput.setAttribute(’name’,'file[]‘);
newinput.setAttribute(’onclick’,'remElement(divFiles,’+inpname+’)');
newinput.setAttribute(’style’,'width:100%;’);
inp.appendChild(newinput);
}

function remElementOld(campo,numero) {
var d = document.getElementById(campo);
d.parentElement.removeChild(numero);
}

function remElement(campo,numero) {
var d = document.getElementById(campo);
alert(campo + ‘= ‘ + numero);
}

149.mmp

September 20th, 2006 at 12:06 am

Hai!

How does GMail adds the file Input fields dynamically when composing a mail.

Yahoo does it by having 50 file Input fields out of which 5 are displayed and 45 are
hidden initially and later displayed on clicking Attach More Files button.

Usually most of the known browsers doesn’t support dynamic addition of file Input
fields(for security reasons). But I wonder how GMail manages this issue.
Am aware that GMail is built on AJAX, but how do they handle this file Input field issue.
Can any one help me out? I just want the logic behind it.

Thanks in advance.

150.glen

September 20th, 2006 at 4:23 pm

I apologize if this topic has already been covered, but I need a little help getting file input
working… thought I had it but can’t get it to work.

Reply 149 sheds a little light on the fact that maybe what I’m trying to do basically won’t
work the way I’m trying to do it? Here’s my code…

Remove Attachment“;
ni.appendChild(newdiv);
}

function removeEvent(divNum)
{
var d = document.getElementById(’myDiv’);
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}

If a file needs to be included (such as a logo, word document, etc)attach it here with the
Browse button.

Add Another File

Basically the first file they put in the file form will be named ‘uploadedfile’ and then
when they click “Add Another File” that one will be ‘uploadedfile1′ then ‘uploadedfile2′
etc. Whenever I try and use the script it only emails the first file. Any ideas?

Looks like it should work but are there security settings that don’t allow this?

Thanks

151.glen

September 20th, 2006 at 4:27 pm

here’s the code again sorry about the double post.


angle brackets are replaced w/ square ones.
The add event function…

var ni = document.getElementById(’myDiv’);
var numi = document.getElementById(’theValue’);
var num = (document.getElementById(”theValue”).value -1)+ 2;
numi.value = num;
var divIdName = “my”+num+”Div”;
var newdiv = document.createElement(’div’);
newdiv.setAttribute(”id”,divIdName);
newdiv.innerHTML = “[input name=\"uploadedfile"+num+"\" type=\"file\" size=\"50\" /]
[a href=\"javascript:;\" onclick=\"removeEvent(\'"+divIdName+"\')\"]Remove
Attachment[/a]“;
ni.appendChild(newdiv);

152.Vishal

September 27th, 2006 at 4:14 am

Apart from my comments, I have a tiny question. Can I use the same logic to dynamically
update structure of a table?
Thanks

153.sairam

September 28th, 2006 at 5:52 am

I cant get any output with this code

154.Godfrey

October 2nd, 2006 at 2:22 am

Hello, I need some help with some javascript coding.

I am displaying some data using a dynamic table created by coding below.The coding
below adds one row with 6 cells to the table. The last column in the table contains a
button to delete the row.

//==============================FUNCTION ADD NEW


ROW=============================
var count = “1″;
var GrandTotalPrice=0.00;
function addRow(in_tbl_name)
{
var sel = document.getElementById(”txtStockCode”);
var sel2 = document.getElementById(”txtStockName”);
var sel3 = document.getElementById(”txtStockQuantity”);
var sel4 = document.getElementById(”txtStockPrice”);
var sel5 = document.getElementById(”txtTotalPrice”);

if(document.frmsin.txtstockcode[document.frmsin.txtstockcode.selectedIndex].text
==’Select Stock Code’ || document.frmsin.txtStockQuantity.value ==”" )
{
alert(’Please Fill in All Data’);
return;
}
else
{

var tbody =
document.getElementById(in_tbl_name).getElementsByTagName(”TBODY”)[0];
// create row
var row = document.createElement(”TR”);

// create table cell 1


var td1 = document.createElement(”TD”)
var strHtml1 = ” ” + sel.options[sel.selectedIndex].text + “”;
td1.innerHTML = strHtml1.replace(/!count!/g,count);
td1.setAttribute(’id’, ‘td1_’ + count,0);

// create table cell 2


var td2 = document.createElement(”TD”)
var strHtml2 = “” + document.frmsin.txtStockName.value + “”;
td2.innerHTML = strHtml2.replace(/!count!/g,count);
td2.setAttribute(’id’, ‘td2_’ + count,0);

// create table cell 3


var td3 = document.createElement(”TD”)
var strHtml3 = “” + document.frmsin.txtStockPrice.value + “”;
td3.innerHTML = strHtml3.replace(/!count!/g,count);
td3.setAttribute(’id’, ‘td3_’ + count,0);

// create table cell 4


var td4 = document.createElement(”TD”)
var strHtml4 = “” + document.frmsin.txtStockQuantity.value + “”;
td4.innerHTML = strHtml4.replace(/!count!/g,count);
td4.setAttribute(’id’, ‘td4_’ + count,0);

// create table cell 4


var td5 = document.createElement(”TD”)
var strHtml5 = “” + document.frmsin.txtTotalPrice.value + “”;
td5.innerHTML = strHtml5.replace(/!count!/g,count);
GrandTotalPrice = eval(GrandTotalPrice) + eval(document.frmsin.txtTotalPrice.value)
document.frmsin.txtGrandTotalPrice.value = GrandTotalPrice
td5.setAttribute(’id’, ‘td5_’ + count,0);

// create table cell 6


var td6 = document.createElement(”TD”)
var strHtml6 = “”;
td6.innerHTML = strHtml6.replace(/!count!/g,count);
td6.setAttribute(’id’, ‘td6_’ + count,0);

// append data to row


row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
row.appendChild(td5);
row.appendChild(td6);
// add to count variable
count = parseInt(count) + 1;
// append row to table
tbody.appendChild(row);
document.frmsin.txtStockQuantity.value =”"
document.frmsin.txtTotalPrice.value=”"

}
}

//======================FUNCTION DELETE
ROW=====================================
function delRow()
{
//var current = window.event.srcElement;
var current = window.event.srcElement;
//here we will delete the line
while ( (current = current.parentElement) && current.tagName !=”TR”);
current.parentElement.removeChild(current);
// var allTDs = document.getElementsByTagName(”td”);
//var firstTD = allTDs.item(0).id;
//var lastTD = allTDs.item(allTDs.length-1).id;
//var str = “# of table cells: ” + allTDs.length + “\n”;
//str += “First TD: ” + firstTD + “\n”;
//str += “Last TD: ” + lastTD;
//alert(str);
}

//========================END
FUNCTION==========================================
I have created a single textbox below to show the Grand Total Price (TotalPrice1+
TotalPrice2 + so on…)Everytime the function addRow fires, the Grand Total Price will
be updated with this statement.

GrandTotalPrice = eval(GrandTotalPrice) + eval(document.frmsin.txtTotalPrice.value)


document.frmsin.txtGrandTotalPrice.value = GrandTotalPrice

However when I delete a row, the value of Grand Total Price textbox stays the same and
not updated. How can I update the Grand Total Price value when I delete a row?
Hopefully someone canhelp. Thanks.

155.SandiPawar

October 12th, 2006 at 7:50 am

Hi, I have added div dynamically to parent div using above code. IT is added successfully
but when I view source code by right clicking on page. It is not showing me newlly added
div elments anywhere on page. Hence I am not able to do any operation with them. Can
any one please help me on this. I have want to move(draggable) these newly added child
div elements to some other place on page. For moving elements I am using some third
party javascript library. But is it because that elements are not get added properly they are
not availble for further operation. Please reply soon.It’s very urgent. Thanking you, Sandi

156.m.k

October 16th, 2006 at 3:53 am

Thanks for this.

157.mihai

October 17th, 2006 at 7:37 am

Hi,
I am having this prblem on IE6 with the following code:

var form = document.forms[0];


var tbl = document.getElementById(”table6″);
var row = tbl.insertRow();

var cell0 = row.insertCell(0);


var checkField = document.createElement(”input”);
checkField.setAttribute(”type”, “checkbox”);
checkField.setAttribute(”name”, “checkItem”);
checkField.setAttribute(”id”,”checkItemNew”);
cell0.appendChild(checkField);
var cell1 = row.insertCell(1);
var scCd = document.createElement(”input”);
scCd.setAttribute(”type”, “text”);
scCd.setAttribute(”name”,”scoreCodeNew”);
scCd.setAttribute(”id”, “scoreCodeNew”);

//***********************************************************
//scCd.setAttribute(’onChange’,’saveChanges()’);
//scCd.innerHTML = ” onChange=\’javascript:saveChanges();’\”;
//scCd.onChange = saveChanges();
//***********************************************************

cell1.appendChild(scCd);

It looks that I have the same problem like others to call on “onchange” event of the new
created element this method saveChanges(). I tried all the above but with no luck.
Please give me a hint !!!! Regards !

158.mihai

October 17th, 2006 at 7:52 am

This line is working now !!!

scCd.onchange = saveChanges;

Event Name must be lower case !!!


I hope it helps others !!!

Mihai

159.Salman

October 20th, 2006 at 5:29 am

THANKS!
Great script and very usefull in my current project, I had a little problem with firefox not
getting submitted variables from dynamic fields but Adriaan’s idea worked, just moved
[form] tags outside the tables and it started working (Y)

* Salman likes it!

160.John

October 23rd, 2006 at 3:15 am

Reply on:
SandiPawar
October 12th, 2006 at 7:50 am

Hi, I have added div dynamically to parent div using above code. IT is added successfully
but when I view source code by right clicking on page. It is not showing me newlly added
div elments anywhere on page. Hence I am not able to do any operation with them. Can
any one please help me on this. I have want to move(draggable) these newly added child
div elements to some other place on page. For moving elements I am using some third
party javascript library. But is it because that elements are not get added properly they are
not availble for further operation. Please reply soon.It‪s very urgent. Thanking you,
Sandi

#######################################################################
####

Hi Sandi

I had the same problem. The only way to actually see what items have been added, is to
add the values of the added items to an extra control (listbox), then set a textbox = to the
listbox. Then you will be able to get the values. This is great for when you are using aspx
because you will be abe to get the values in your aspx code (baring in mind that you must
use a server side textbox).

Hope this helps.

Cheers
John

161.Tvorba stránok

October 23rd, 2006 at 8:27 am

Great article!! It helped me… thanks, Dustin

162.kevin

October 26th, 2006 at 3:37 am

Thanx mate,

newdiv.innerHTML saves me. Nice tutorial dude.

163.Matthew

October 30th, 2006 at 8:22 am


Hi,
It was a chance (and some googling) to bump into this page! I was working on a new user
interface problem where I had to create dynamical form elements.
Thank you for your contribution.

164.Rob

November 1st, 2006 at 5:30 pm

This is a great solution. Thanks!! This cut my code by more than half and solved the
problems associated with it.

165.Keith Greer

November 2nd, 2006 at 7:14 am

Great article, very useful. Will be back here again. Thanks!

166.Mohammed

November 5th, 2006 at 12:41 am

It is a great code. I implemented it.


It add fields fine, but when I remove, it removes based on the ID correctly, but after
fraction of a second it deletes all the elements.
Any ideas.

167.Mohammed

November 5th, 2006 at 1:24 am

Never mind, I got it to work.

Thanks,

168.Mohammed

November 5th, 2006 at 9:47 pm

Any ideas how to get the code to work in IE, it works fine in Firefox.
The code I am using is the same as the code provided at the very beginning of this page.

Thanks,

169.donovan

November 11th, 2006 at 1:05 am


Yo, like your code. I’m adding a version of it to my library. I’ve also included it here for
your edification (it’s brief.. you might like it)

/*this is a general purpose function that keeps you from having to type
'document.getElementById'.. saves time and typing. I use it's like
EVERYWHERE*/
function el(inID) {
return(document.getElementById(inID));
}

/*this function creates an element, appends it to the parent, and then


returns it so you can set it's innerHTML, style and other attributes.
You never know what you're going to need to do after creating one. */
function addElement(inElementType, inElementID, inParentID) {
newEl = document.createElement(inElementType);
newEl.setAttribute('id', inElementID);
el(inParentID).appendChild(newEl);
return(newEl);
}

/*This last function removes the element from it's parent, even without
you having to know who it's parent IS. I considered calling it
'popElement' because it returns the removed element in-case you need it
somewhere... 'removeChild' doesn't really delete the element anyway, so
you may as well be able to keep an handle on it if you want to. */
function removeElement(inID) {
oldEl = el(inID);
parentEl = oldEl.parentNode;
return(parentEl.removeChild(oldEl));
}

I Hope you like the code!

Donovan

170.satish

November 13th, 2006 at 5:11 am

Hi ,

My name is satish , I am new to Java Script ., Regarding help on Java Script..,

When ever on clicking the Attach files Label a new pop up window comes up

with Text Area Having Drag and Drop Files Facility and Buttons (Browse and Remove)
and OK and Cancel Buttons. Now all Buttons are Enabled

According to my requirement , First Remove button is Disabled(when first pop up time)


Second one . when we perform drag and drop a file in text Area , Remove should be
Enabled .

If you have any idea and code please send me

171.saurabh

November 14th, 2006 at 5:06 am

I am working in HTML and i have created a select box and how can i delete a
element/item from a select box.

172.saurabh

November 14th, 2006 at 10:22 pm

Hi
I am saurabh and i am new to HTMl and Java script can any one tell me that how can i
send mail through outlook express with an attachment using HTML or ASP.net

173.Otváranie trezorov

November 17th, 2006 at 2:55 am

I was searching for solution like this for hours and finally I’ve got it! Thanks Dustin, you
helped me :)

174.DuGiNTHaMuD

November 24th, 2006 at 11:36 pm

Not what I had in mind, as to how I was gonna go it, but it works great for what I needed.
THANKS ( Open skull, stir grey matter, does wonders. )

175.Net_Giant

November 27th, 2006 at 4:57 pm

I used something similar in a page at work. I ran across a problem with IE 6 however.
Everything worked as expected when the form was submitted. The problem showed up
when the user hit the back button – the dynamically created controls were gone.
FireFox displayed the dynamic controls just as they were before the form was submitted.
Any ideas?

176.dharmesh

December 4th, 2006 at 11:17 pm


it was really very informative article. it will help me lot.thanks….

177.spiritz

December 6th, 2006 at 6:21 am

thx so much, i decide to use this after picking many other ways ;)

178.Jason

December 6th, 2006 at 12:47 pm

Hi.. Great Function Dustin.

What I need to do is something similar, except I need to is pull some


values from text fields generated.

newdiv.innerHTML = "";

I thought maybe using..

document.frmAnalysis.TestBlah123[0]

would work, but I get “undefined”. Is there a way to even do that?

179.George

December 8th, 2006 at 12:08 pm

Awesome. Very helpful and simple for what I needed. Thx.

180.Guest2#%%$&%^&#$%

December 13th, 2006 at 12:42 pm

I post just to say thank you to -Kim Steinhaug- for posting the solution for that dynamic
content not submitting problem. Saved me from a lot of tests and headaches THANK
YOU

And remember kids! Never nest tags inside of table tags! just set padding and margin of
form tag to 0 to avoid spacing!

181.chochis

December 14th, 2006 at 4:23 am

And now, my two cents:


Have you seen what happens in IE6 (mainly) when you do an appendChild? :-) HTTP
REQUEST FOR THE DOCUMENT! LOL! if you do it 20 times, it will do it 20 times!
In FF it just do it once (what i have seen). I have to keep testing! Im going to rewrite the
appendChild function with innerHTML and see what happens! :-O

182.Gyan

December 18th, 2006 at 3:54 am

How to set background as selected of a Asp.Net2.0 TreeView node using JavaScript when
user clicks on a node?

183.sangeeth

December 21st, 2006 at 10:19 am

i have a requiremnt in my project.i need to add html elements dynamically.after wrting


data..into the rows i have update them in to my database(mysql)…how cani reference the
dynamically created data and update in to the table.

184.Mehul

December 28th, 2006 at 3:03 am

Hi…
Good tips… Thanks…
And does anyone knows answer for above question by Sangeeth. I’ve same kind
requirement too….
Thanks.

185.Ankur

December 30th, 2006 at 3:42 pm

as we can set attribute of any HTML element dynamically


can we set EVENT of HTNL element dynamically with javascript
like onclick event i want to call cancel() function.
i can do this thing in HTML easily but how i can set event of a HTML butoon
dybamically using javascript.

please whatever you know let me know.


it’s urgent.

thnks

186.Ankur

December 30th, 2006 at 3:46 pm


as we can set attribute of any HTML element dynamically
can we set EVENT of HTNL element dynamically with javascript
like onclick event i want to call cancel() function.
i can do this thing in HTML easily but how i can set event of a HTML butoon
dybamically using javascript.

please whatever you know let me know.


it‪s urgent.

if possible then send replay on this mail id also


anks_ce@yahoo.com please

thnks

187.theguyofdoom

January 4th, 2007 at 9:38 am

Hi,

Can you halp me? I can’t make sense of my problem:

I have to add a number of textboxes (the number comes from a textbox) when the box is
changed. I made the folowing code to Dustin’s example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="JavaScript" type="text/javascript">
<!--

function addEvent(times)
{
for (e=1; e <= times ; e )
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById("theValue").value -1) 2;
numi.value = num;
var divIdName = "my" num "Div";
var newdiv = document.createElement('div');
newdiv.setAttribute("id",divIdName);
newdiv.innerHTML = '<tr><td></td><td>time ' num '</td><td
align="center"> <input type="text" name="textbox' num '"</td></tr>';
ni.appendChild(newdiv);
}

//-->
</script>
</head>

<body>
<input type="hidden" value="0" id="theValue" />
<p><a href="javascript:;"
onclick="addEvent(addEvent(document.getElementByID('aantalmobieltjes').
value));">Add Some Elements</a></p>
<input type="text" name="numberoftimes" id="numberoftimes"
onchange="addEvent(document.getElementByID('numberoftimes').value)" />
<div id="myDiv"> </div>

</body>
</html>

Ps: Yes, I’m new to JavaScrit. So if I screwed it…

188.theguyofdoom

January 4th, 2007 at 9:41 am

oops, I forgot to delete the link from Dustin’s code, so an comment:

Ignore the

<p><a href="javascript:;"
onclick="addEvent(addEvent(document.getElementByID(’aantalmobieltjes’).value));">
Add Some Elements</a></p>

code

189.Jayaprakash

January 7th, 2007 at 9:25 pm

Thank you for the cool piece of code..its great.

190.sudeep M

January 9th, 2007 at 6:02 am

Kool stuff, really helped me a lot for dynamic content addition and removal.
Good work indeed.
Thanks

191.A to Z of World

January 11th, 2007 at 1:59 am

I love java script. Thanks for the inof.

192.Hetal
January 11th, 2007 at 12:34 pm

can any1 help me with the above code its giving me error

193.sangeeth

January 16th, 2007 at 1:37 am

i have a row which contains two text boxes and tow list boxes.when i click the add button
i should add(append) a row which contains same elemets.please tell me how can i create
a listbox or select box dynalically.

194.jb

January 18th, 2007 at 9:46 am

Oopz, here’s the code:

newdiv.innerHTML = ‘ VERWIJDER DJ new


Ajax.Autocompleter(”dj[]“,”hint[]“,”autocomplete/dj.php”);’;

195.jb

January 18th, 2007 at 10:06 am

I‪m trying to combine Dustin‪s script with http://wiseguysonly.com/demos/ajax-


autocompletion/autocomplete.php

It works fine in Firefox 2.0, but in IE6 and IE7 the autocomplete field appears, but
doesn‪t work. Can somebody help my figuring out why? Or is it just possible in
Firefox?

P.S. can you delete the other posts?

function addDj()
{
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById("theValue").value -1)+ 2;
numi.value = num;
var divIdName = "my"+num+"Div";
var newdiv = document.createElement('div');
newdiv.setAttribute("id",divIdName);
newdiv.innerHTML = "REMOVE DJnew
Ajax.Autocompleter(\"dj[]\",\"hint[]\",\"autocomplete/dj.php\");";
ni.appendChild(newdiv);
}

function removeDj(divNum)
{
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}

196.Rukshan

January 29th, 2007 at 11:43 pm

Hi guys,
i got it working.. again it was some thing to do with the ‘newdiv.innerHTML’ code block
i placed two double quotes in either side of removeElement() function’s parameter like
this,

onclick=removeElement(”‘+divIdName+’”)

earlier it was like,

onclick=removeElement(’+divIdName+’)
(without the double quotes)

197.Ian

January 30th, 2007 at 4:50 pm

Thankyou, Thankyou, Thankyou

I have been slapping my head against a desk for three hours trying to sort this out.

Great solution, simply put for the stupid people (of which I proudly count myself)

Cheers

198.delmoras

February 7th, 2007 at 3:58 am

awesome!just what i was looking for!!!

199.Nate

February 12th, 2007 at 11:54 am

I need to create a image upload script that adds a thumbnail, caption text input box, and a
delete link for every image that the user selects. Anyone care to help me with that?

200.Imtiaz
March 11th, 2007 at 11:00 am

Hi

I would like to know how to obtain the tag name of elements that are created dynamically
using AJAX and DOM Technologies as these cannot be obtain by simply viewing the
source of the page.

Thanks

201.Dave

March 14th, 2007 at 9:46 am

Hi quick question. I use dom to make a dropdown on the fly and then use ajax to populate
that dropdown from an xml file straight away after it creation, but It doesn’t seem to
work. If I use a ‘reqular html’ dropdown I can add to it. Can this be done?

202.Paul

March 15th, 2007 at 4:51 pm

Thanks a ton Dustin! You should write a book. Also, thanks to Donovan for his solution
to delete. This has saved me a ton of time.

203.Nick

March 16th, 2007 at 2:21 pm

Aside from the tons of junk replies here…


I just wanted to send a quick thanks Dustin.
I needed to dynamically add fields to a form, and this is perfect. Worked flawlessly the
first attempt.

And the reason this page is seeing so much traffic probably is because it’s the 2nd hit on
google’s results when I searched for “dynamically add form field” with the 1st hit being
completely useless and worthless.

Thanks again. I think I’ll be bookmarking this site for future references.

204.Pal

March 19th, 2007 at 7:30 am

Thanks very helpful.

205.Tom
March 20th, 2007 at 5:12 pm

Hi is possible LIMIT number of new elements? for ex: I want is possible add just 3 text
field 0:-)
thnx for help

206.David

March 26th, 2007 at 12:09 am

This is a new vision of your revove function

function removeEvent(divNum)
{
var d = document.getElementById(divNum).parentNode;
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}

207.David

March 26th, 2007 at 1:03 am

function addEvent()
{
var ni = document.getElementById(’myDiv’);
var numi = document.getElementById(’theValue’);
var num = (document.getElementById(”theValue”).value -1)+ 2;
numi.value = num;
var divIdName = “my”+num+”Div”;
var newdiv = document.createElement(’div’);
newdiv.setAttribute(”id”,divIdName);
newdiv.innerHTML = “Element Number “+num+” has been added! Remove the div
"”+divIdName+”"“;
ni.appendChild(newdiv);
}

function removeEvent(divNum)
{
divNum.parentNode.parentNode.removeChild(divNum.parentNode);
}

Hi, and this is a new function for delete element without an “id”!
to remove element you can use this call: removeEvent(this)

Bye, David
208.Erika

March 26th, 2007 at 6:13 am

Thank you, this was really usefull, exactly what i need.

209.me

March 29th, 2007 at 9:00 pm

When you publish something like this, make sure it works. Unless you want us to spend
30 minutes trying to figure out you do not know how to open and close quotes.

your javascript here does not work:

newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! Remove the div
“‘+divIdName+’”‘;

it should be like this:

newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! Remove the div
“‘+divIdName+’”‘;

I hate to copy and paste something that does not work thinking that you know what you
are doing. I mean, did you try it before copying your code?

geeee

210.Sunil

March 31st, 2007 at 1:05 pm

hi every one

I want to Pass array from jsp page to servlet

the problem is. array is in javascript which contains value of appended row by some
codes give above and there is no limit to the array.

Can any one help me in that PLZ mail me any code any one know …….

Thanx

211.Masa

April 4th, 2007 at 5:19 am


Hi, I have a problem with that removing part. I have a HTML element SELECT with
onchange. Everytime I change selected options, I call this addElement function. There I
have an array which I loop. In my loop I add new div tags under my SELECT box. My
problem is how to remove old divs when onChange come again? I don

212.Deep

April 4th, 2007 at 2:13 pm

According to me, I think that the http protocol will not help us to pass the array of
elements from the UI to teh servlet, we need to pass each of them individually and get
them using Request.GetParameters() and create the array out of it.

Pls let me know if I am wrong.

213.Atul Ojha

April 11th, 2007 at 9:46 am

Awesome Man,Dynamic removal of HTML controls helped me a lot in AJAX

Thanks a lot..:-)

214.dustin

April 13th, 2007 at 2:10 pm

can anyone has validation code for the dynamically created select box and checkbox?
when i submit the form i want to make sure the user has selected a option in the select
box? thanks

215.Shaun

April 17th, 2007 at 6:39 pm

Hey I am using your techniques to add elements to my DOM…

It works fine however when the new element is added it ignores the css file.

I did remember to set the class attribute for my new img element and I’m
sure that it is being inserted in the write place because I am
getting the elements that I am inserting it before using

var elementid = getElementById(”elementid”);

and also getting the parrent element the same way


var parentelement = getElementById(”parentelementid”);

and then I am inserting it using

parentelement.insertBefore(newelement, elementid);

this all works fine the new element is inserted however the new element
does not respond to changes in the css file even though I am making sure to
set the class attribute like this

newelement.setAttribute(”class”, “newelementcss”);

it is so weird I cant even get it to go hidden using

.newelementcss{visibility:hidden;}; and at this point it is driving me mad…

Can anyone figure this one out…..

216.Shaun

April 17th, 2007 at 10:57 pm

Never mind….

I changed the following in my CSS file and presto…

Instead of using .elementclassname

I used this instead because the element I created is an img …

img#elementidname

Look closely at the last line and Notice that I am not using the “class”- attribute
of the img element at all … Now I am referencing the img element by it
“Id”- attribute ….

Hope this helps someone….

217.raj

April 19th, 2007 at 2:19 am

hi,
In my page i have a select box and anchor tag add.when we click on add
it should add one more select box and continue using javascript.
same for remove the select box.
please help me.

Regards,
raj.
honey_mysunny@yahoo.com

218.ramesh

April 20th, 2007 at 5:09 am

/***********************************************************************
**************************
/****************************This is used to create text boxes
dynamically************************
/**************************ramesh 1240 from pragathi engg college
/***********************************************************************
************************

count = 0;

function showPercent()
{

if(count == 0)
{
creatingfields();
document.getElementById(’tblHeirNames’).style.display = ‘block’;

}
else if(count > 0)
{
var s = validfunction();
if(s == true)
creatingfields();

count = 0;

}
function creatingfields()
{
htmlText = ” “;
htmlText += “Item Name”;
htmlText += “”;
htmlText += “”;
htmlText += “”;
htmlText += “Price”;
htmlText += “”;
htmlText += “”;
htmlText += “”;
count++;
regExp = /(\@)(\S+)(\@)/g;
htmlText = htmlText.replace(regExp, “$2″+count);
document.getElementById(”tblHeirNames”).innerHTML += htmlText;
//tblHeirNames.innerHTML += htmlText;
}

function removeElement(tblHeirNames)
{

// document.getElementById(’tblHeirNames’).style.display = ‘none’;
// var d = document.getElementById(”tblHeirNames”).parentElement

var d = document.getElementById(’tblHeirNames’);
var olddiv = document.getElementById(divNum);
d.removeChild(d.lastChild);

219.Dru

April 24th, 2007 at 8:48 am

Hi All,

Am trying to use this to upload multiple files with a php script, but am having trouble
implementing. Can someone give pointers? How do you keep track of how many input
elements there are –since the PHP script needs to know how many times to iterate
through the file handling loop, right? Also, what if I’d like to add not only a file, but also
a text-field caption and a radio-button element to each uploaded file? Many thanks!

–Dru

220.Nathan

April 25th, 2007 at 5:05 am

Is it possible to change this from a div to an add / delete table?

Any thanks appreciated.

Regards
Nate

221.kumar

April 26th, 2007 at 12:11 am

hi

i have a doubt in that area, i have one text field that is user for enter the no of fields.
suppose i entered 3 means then 3 text fields are added dynamically. how its possible.

thanks in advance

bye kumar

222.kumar

April 26th, 2007 at 12:16 am

hi

i have a doubt in that area, i have one text field that is used for enter the no of fields.
suppose i entered 3 means then 3 text fields are added dynamically. how its possible.

Enter no of fields ———(text field)

submit

when i click submit

it will show belove this

———(text field) ———–(text field)


———(text field) ———–(text field)
———(text field) ———–(text field)

thanks in advance

bye kumar

223.sarvesh

April 26th, 2007 at 11:00 pm

hi everybody,
i used the same code with selectboxes but when the form is posted values are not coming
224.sarvesh

April 26th, 2007 at 11:04 pm

hi everybody,

i used the same code with selectboxes but when the form is posted values are not coming

its not coming in mozilla where as it is coming in internet explorer. How to overcome

this scenario. if anyone find the solution plz forward it to my mail . my e-mail id

nsarvesh@rediffmail.com

225.Silviu

April 27th, 2007 at 2:09 pm

Justin,

Have you tried putting this code inside a table? I am having major difficulties with IE and
tables…

226.mudit sharma

May 4th, 2007 at 1:17 am

hi,
I’m creating a context menu. facing problem when user re-goes to the page.every time we
go to page the context menu item list gets longer.I’m not able to delete element and then
create context menu with same id. following is my code in .js file.

ManageRolesController.prototype.initContextMenu = function () {

this.contextMenu = document.getElementById(”contextmenu”);
this.contextMenu =new YAHOO.widget.ContextMenu(”contextmenu”, { trigger:
this.pageView.dataTable.getBody() } );
this.contextMenu.addItem(”Delete Item”);
this.contextMenu.addItem(”View Item”);
this.contextMenu.addItem(”Edit Item”);
}
this.contextMenu.render(document.body);
this.contextMenu.clickEvent.subscribe(this.onContextMenuClick.createDelegate(this));
};

please suggest a solution……..


227.Rik Weber

May 8th, 2007 at 9:39 am

Silviu,

I did some dynamic table creating a few years back, you might find something you’re
looking for here http://www.rikscottweber.bravehost.com

I had problems with IE which I kinda fixed, think it’s something to do with including the
“tbody” tag in your markup.

Hope this helps.

228.Edgars

May 8th, 2007 at 4:08 pm

I’m trying to add a new image to existing div. Everything is working in Firefox, but in IE
something is not working as it should. Some part IE is doing correctly, but not exactly
setting up attribute style. Generally it adds image and finds its source path, but thats it-
nothing more.
My code looks like this:

1. function addImage_l(src,x,y) {
2. var layer= document.getElementById(’ImgLayer_l’);
3. var newimg = document.createElement(’img’);
4. var ImgIdName = ‘img1′;
5. newimg.setAttribute(’id’,ImgIdName);
6. newimg.setAttribute(’style’,'top:’+x+’px;left:’+y+’px;position:relative;’);
7. newimg.setAttribute(’src’,src);
8. layer.appendChild(newimg);
9. }

My problem is that line 6. is not working on IE. But if I manually create this image in
HTML code and set the same style - it is working.

IF SOMEONE HAS AN IDEA HOW TO SOLVE IT, PLEASE HELP.

229.vinay

May 10th, 2007 at 11:18 pm

HI all ,
I have included one dragdrop script.
The page creates one table and drag and drop works fine in that page , however as per
one need I created that table in that page via javascript ..
some thing like

html=”….” ;
document.getElementById(’table’).innerHTML = html;

But now the drag and drop is not working.

any suugestions will be highly appreciated.


thanks
vinay.145@gmail.com

230.ldavid20

May 14th, 2007 at 10:11 am

I would like to know if anyone has any idea to that the num variable and turn it into a php
variable. What I need to do is to count the number of additions and add them to a
database.

any help is appreciated.

231.ldavid20

May 14th, 2007 at 10:42 am

Nevermind… the number of instances is in the form “theValue”.

232.Luke

May 14th, 2007 at 2:17 pm

I need to be able to keep track of how many elements have been added. I need this
because I am using the script for an event registration form. When somone registers they
have the ability to add addtional attendee’s. I then will take this number of additional
attendees and add that number to the database. I can do this perfectly fine except when i
add an element and then delete it. When i do this the number in the database is not
correct, the number in the database lists the number of times i added an element but does
not take into consideration when i delete the element. any clues on how to be able to keep
track of this would be very welcome.

thanks

233.sapan

May 16th, 2007 at 3:49 am


hi all plz help me to solve this problem

my problem is

in my current jsp page i have a textfield and a button


when i click search button then the result will have to display below that page

234.Kirti

May 26th, 2007 at 2:49 am

I used your code to create text boxe.Its working but in case of error i want to start the
hidden field value (theValue) with 0 but its starting from last value onwards.

In my form i have 6 editable fields and one button.When i click on that button i am
generating a text box(name1).Now user entered all the value in all the text boxes.And
pressed save but some error came.Now in form all the values are coming except that text
box.I entered proper value and create a text box by clicking on the button but this time its
id is name2 but it should be name1.
I am getting exception in my for loop.
Please suggest me some solution.

235.Dave-0

May 28th, 2007 at 6:03 am

ok that didnt copy right, so ill post it again, i tried posting a link earlier but it didnt work
either lol

hxxp://sypher.kwikphp.com/dynamic.html

236.bensamuel

May 28th, 2007 at 7:01 am

i would like to know how would you set the no wrap attribute for a column created
dynamically using java script, even though i set the width to a specific value and set the
nowrap attribute as true/nowrap the column gets wrapped to the size of the text can
anyone help me please… the same thing is working fine in firefox… but creating a
problem in IE

237.Dave

May 28th, 2007 at 8:21 am


How would this code work in regards to updating an order confirmation.
The confirmtion displays the input and has hidden fields. I would want to
be able to edit each element and update the hidden fields.

Can you post a sample?

238.Mohamed

May 28th, 2007 at 10:32 pm

Hai Dustin,

This article very much used for learners, u done a great job. I have one question regarding
this add and remove element. I used ur coding in my application, i need one help i have to
get the remaining element after removing the Child node. Please help me regarding this.

thanks

239.Guilherme

May 30th, 2007 at 11:13 pm

Hi Dustin, this is lots of comments you get here, maybe the answer I look for is in one of
those, but I just couldnt read it all. Hope you can point it to me so, if it is there actually.

Well first thing that got me curious is why youre incrementing your counter doing:
.value -1 + 2, instead of just .value + 1, or .value++ ?

second, Id like to know what is the difference between doing this two things:
element.attribute = value;
element.setAttribute(’attribute’,'value’);
?

finally, I want to assign this element’s ID after I create it. Should I (or could I) use
element.id = value or the setAttribute function? It get us back to the previous question.
My issue with the setAttribute is also that it doesnt work really well with the Internet
Explorer (or the IE doesnt work well at all, should we correct the viewpoint of it).

Hope you can help me out. Nice work youre doing here, I like the collapsing windows.
(how you do that?)

Peace.

240.Bala

May 30th, 2007 at 11:46 pm


hi all

i have created a website for franchise entries.i have created a link named “Add franchise
to request list” for each franchise,if a user clicks more than one franchise it has to be
added in a container with checkbox selected.Then clicking the submit button should pass
that information to administrator.

I want a javascript for this.

Please advise me.

241.Villa rentals

June 2nd, 2007 at 3:44 pm

Hi,

I used it just now and works very good. It was hard to find removeElement on w3schools
website, so I’m glad to see that :) I was doing ajax so HTML DOM is very good for that
solutions.
CHeers
R

242.mdpai

June 17th, 2007 at 10:33 pm

thanks for the great articles, consider i just raped it :P

243.sirdarckcat

June 18th, 2007 at 11:06 pm

Hi!

I think you will love the following document, about how to interact with a webpage using
javascript, with the address bar (one of the chapters use the functions you are using here),
this is called javascript inline debugger:

http://jasildbg.googlepages.com/

de document is available for download here:

http://jasildbg.googlepages.com/en

it’s really fun


Greetz!!

244.Patricia

June 22nd, 2007 at 6:16 pm

For the first time the very first result of my google search was exactly what i was looking
for! This is exactly what i was trying to do but was just using innerHTML to add the divs
inside the others and it was mostly working but this is so much better. Thanks!

245.Sevi

July 10th, 2007 at 3:46 am

Hello,
The code works beautifully. I am creating form fields with it. No problem with Safari, but
with most of the main browsers IE, FireFox etc. after submitting the form if the user hits
the back button, every thing disappears, and the data which was inserted using
dynamically created fields is lost.
I will appreciate if some one worked this out would let me know how.
sevi.

246.Ali

July 11th, 2007 at 8:26 am

I am new Java Script programmer and recently learning more about DOM HTML I want
to know how to create and Unordered list dynamically when some enters some text in
text box the text should be displayed in list form one below the other preserving older
entries.

247.sanjay shiwakoti

July 12th, 2007 at 5:06 am

I’ve these two function


addRow works fine which add the entire row with the elements
but removeElement is not working Can somebody know how to remove these node
cause i’m newbie
function addRow(id,value1,value2,value3){

var index = document.getElementById(”aValue”).value;


var tbody = document.getElementById(id).getElementsByTagName(”TBODY”)[0];
var row = document.createElement(”TR”);
row.setAttribute(”id”,”row” + index);
input1 = document.createElement(”textarea”);
input1.setAttribute(”name”,”goal_desc” +index);
input1.setAttribute(”cols”,”80″);
input1.setAttribute(”rows”,”10″);
input1.setAttribute(”class”,”textareaBig”);
//document.input1.focus();
//input1.value =”";

input2 = document.createElement(”input”);
input2.setAttribute(”name”,”goal_wt” +index);
input2.setAttribute(”value”,”");
input2.setAttribute(”type”,”text”);
input2.setAttribute(”size”,”10″);
input2.setAttribute(”maxlength”,”3″);

input3 = document.createElement(”textarea”);
input3.setAttribute(”name”,”goal_remarks” +index);
input3.setAttribute(”cols”,”80″);
input3.setAttribute(”rows”,”10″);
input3.setAttribute(”class”,”textareaBig”);

var td1 = document.createElement(”TD”)


td1.appendChild (input1)

var td2 = document.createElement(”TD”)


td2.setAttribute(”align”,”left”)
td2.setAttribute(”valign”,”top”)
td2.appendChild (input2)

var td3 = document.createElement(”TD”)


td3.appendChild (input3);
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);

tbody.appendChild(row);

//increase index of hidden field


index++
document.goal.aValue.value=index
}

function removeElement(tid) {
//var tbody = document.getElementById(”myTable”);

var row=document.getElementById(tid);
// var trainer = document.getElementById(’displayForm’);
//var olddiv = document.getElementById(divNum);
var tbody=row.parentElement;
tbody.removeChild(row);

248.Slevdi Davoteca

July 13th, 2007 at 3:17 pm

Sevi is right! Appended elements disappear when either the forward or back buttons are
used to return to the page. Not in Firefox though.

Unfortunately, only 2% of my users browse with Firefox so I need to solve this.

It looks like the browser’s cache in IE is not updated with the appended elements in IE.
Does anyone know how to make this happen? An MS Ajax or DHTML expert might be
able to help:-)

249.Asifa

July 24th, 2007 at 7:57 am

Thank you for this article. This is exactly what I needed.

250.Vivek Bajpai

July 30th, 2007 at 5:50 am

Hello All,
This Adding Dynamic Elements Post is really very much interesting & useful for the New
Web 2.0 Technologies stuff. The Code was very beautifully written, but please can any
one provide me a solution, i am stuck with it. “innerHTML” is a property that is not
appropriate with the W3C Standards,
in IE 6.0 When we post the elements we can easily retrieve the POST data & can enter
the POST info into the database, I have tried that & thats very useful, thanks.
With Firefox, we can easily Add the Elements, But WE CANT RETRIEVE THE
VALUES THROGH THE POST ELEMENT. Please Help me if we can use something
other then innerHTML, or we can retrieve the POST data in Firefox.
Thanx in Advance…

251.Vivek Bajpai

July 30th, 2007 at 6:03 am


Hello All,
I am so sorry, i just read the article fully now, & i got the solution in the same article,
thanks very very much to Kim Steinhaug
Who posted the Solution to the above query on July 6th, 2006 at 9:49 am. I am now able
to add the data from both the IE & Firefox.
thanks kim, but how does

form
table

is different from

table
form

Anyways, thanks a lost Kim & Dustin u too for such a beatifukl place to share the ideas
that W3C do not Share.

Original Message by Kim :


_______________________________________________________

Use this technique

form
table

instead of

table
form
_______________________________________________________

252.drozi

August 9th, 2007 at 2:55 am

.parentNode working IE, Opera, Firefox

253.Abhimanyu

August 29th, 2007 at 4:46 am

Helllo,
I am trying to use this code for creating some dynamic text boxes WITH SOME
HIERACHY IN BETWEEN THEM.
What I mean is If i create a text box then i should be able to create sub-level ( another
text box under) for the text box and then if required another sub-sub level under that.

Visit the link : http://www.b3staging.com/abhi_b3sitecreator/test2.htm


to understand what i mean.

Can anybody help me in this.

Thanks,
Abhimanyu.

254.shah

August 30th, 2007 at 3:52 am

i want to send html editor data to server side page through query string.plz help required
in this regard.
bcz the data include html,&nbsp etc so how i could handle this

255.Robbin

September 5th, 2007 at 2:56 am

Hi! I was wondering if there possible to set a limit to how meny elements you can add.
And if I want to use this script to more than one element, is that possible?

I want to use this script of adding ’s insted of ’s, is that possible

Sorry for my bad english.

Kind Regards Robbin

256.Jon

September 14th, 2007 at 1:11 pm

for deleting/removing an element, why not do:

function removeElement(elemId) {
var d = document.getElementById(elemId);
d.parentNode.removeChild(d);
}
then you can delete any node in the document just by it’s id, which should be unique, and
you don’t need to know the name of the parent. if you use prototype you can shorten it to
this (which you might not even need to make a separate function for):

function removeElement(elemId) {
$(elemId).parentNode.removeChild($(elemId));
}

that last one (or something similar) may also work for others such as jquery but i’m not
as familiar with those

257.srinivas

September 18th, 2007 at 11:11 pm

Hi Justin,

I am Srinivas, I am working with JSP and HTMl. I need to add text field dynamically.

Exact problem: There will be many question in a page. when i click on the question
answer should be displayed in new text field or text area. And i will take care of
retrieving the data from database.

Thanks & Best Regards,


Srinivas..

258.Bala Krishna

September 22nd, 2007 at 1:23 am

I am also facing same problem. I am adding form field dynamically. but when is submit
form, newly added field does not recognized by php in FF but works perfectly in IE.
Does anyone have solution. Please tell if any?

259.Andy

September 28th, 2007 at 1:02 pm

Does anyone know how to add cookie functionality to this script? It would be great to
have the list saved for future visits.

260.martti

October 6th, 2007 at 2:22 am


I’m trying to add a new image to existing div. Everything is working
in Firefox, but in IE something is not working as it should. Some part
IE is doing correctly, but not exactly setting up attribute style.
Generally it adds image and finds its source path, but thats it-nothing
more.
My code looks like this:

1. function addImage_l(src,x,y) {
2. var layer= document.getElementById(’ImgLayer_l’);
3. var newimg = document.createElement(’img’);
4. var ImgIdName = ‘img1′;
5. newimg.setAttribute(’id’,ImgIdName);
6.
newimg.setAttribute(’style’,'top:’+x+’px;left:’+y+’px;posit
ion:relative;’);
7. newimg.setAttribute(’src’,src);
8. layer.appendChild(newimg);
9. }

My problem is that line 6. is not working on IE. But if I manually


create this image in HTML code and set the same style - it is working.

IF SOMEONE HAS AN IDEA HOW TO SOLVE IT, PLEASE HELP.

i have the same problem. please help.

261.Giz Galor

October 10th, 2007 at 6:27 pm

Excellent stuff.
Got me out of a tight spot!

262.ColdFusion Developer

October 29th, 2007 at 4:07 pm

Thank you so much for posting this article. I used the following solution which worked
for me:

var elementToDelete = document.getElementById(’xxxx’);


elementToDelete .parentNode.removeChild(elementToDelete );

263.ador

November 8th, 2007 at 3:33 am

Thanks for this code. Works great. I needed something that would make a dynamic
number of objects to be displayed (working on displaying a map and plotting different car
locations at certain times). Good thing I found this site early, it saved me a headache from
researching a ton.

Thanks again.

264.pavan

November 14th, 2007 at 1:25 am

Hello,

I am pavan, i have one doubt, when i create dynamically any element, it is working but
when i try to see viewsource through any browser, am not finding the dynamically
created elements.

how can we get the dynamically created elements in viewsource,

thanks
pavan

265.Brian

November 16th, 2007 at 7:22 am

Dustin,
So glad I found this posting!!! I am using very similar script on an intranet page and have
hit a brick wall. I am using it to create dynamic options so the user can add lines as
needed that contain “option” lines within them. You can see my code here -
http://www.thescripts.com/forum/showthread.php?p=2934648#post2934648

You will probably notice that I am fairly new to all of this and it has frustrated me to no
end. Everything seems to work great but I can’t retrieve the dynamically created values
when the form is submitted.

If you have any ideas as to why this isn’t working, that would be excellent.

Thanks in advance - Brian

266.Sree

December 5th, 2007 at 5:28 am

Oops! I goofed up!Heres the data that I’m trying to clean before I insert new data.

<div id="search_results">
<a href="javascript:myclick(1)">ABC</a><br>
<a href="javascript:myclick(2)">DEF</a><br>
<a href="javascript:myclick(3)">GHI</a><br>
<a href="javascript:myclick(4)">JKL</a><br>
<a href="javascript:myclick(5)">MNO</a><br></div>

Thanks
Sree

267.Dukacar

December 5th, 2007 at 6:38 am

Hello all,

regarding the question of many: “POST DOES NOT WORK WITH FF”.

You must form you HTML correctly: form, table, /table, /form, BUT it is not all.

When creating form elements: text, select, …, you must not create them with innerHTML
but with DOM functions like in post from sanjay shiwakoti (July 12th, 2007 at 5:06 am).

in this way it will work!

Thanks for great code.

268.Dukacar

December 5th, 2007 at 6:51 am

This is add to previous comment.

You can try replacing innerHTML with DOM functions but it should work with HTML
formed correctly.

269.Sathish Raja

December 9th, 2007 at 10:49 pm

I am working with asp.net 2.0.


With your script i have dynamically added div elements to my panel. Upon postback i
want use this div elements in my server coding. Is it possible for me to access those
elements on server side. please help on this.

repyl asap.

270.Bradley Hook

December 18th, 2007 at 11:44 pm


Thanks Dustin!

I built this into a form and it works beautifully. You’re a legend.

271.Jimmithy

December 19th, 2007 at 8:04 am

You should note that when creating elements dynamically with javascipt, most all
attributes are set to read only…so basically if I wanted to do something like this, it would
not work…
———-

and for the js


function add(){
var newElem = document.createElement('li');
newElem.setAttribute('name','newattributename');
}

runction remove(){
var createdElem = document.getElementsByName('newattributename');
}

———————-
The browser won’t be able to find the element you created(unless you are using Firefox)
and you will have all sorts of problems.

At the moment I have no idea’s on how to make this work on all browsers…I’m
beginning to think that relying on javascript is a bad idea.

If anyone has any solutions, let me know.

272.Jimmithy

December 19th, 2007 at 8:05 am

In my recent post there was supposed to be some HTML that didn’t go through…

basically it was one input that called the function add() and one that called the function
remove() using onclick(although how I call it isn’t really important.)

273.Sowmya

January 16th, 2008 at 12:37 am

Beautiful javascript. I thank you having it here. It works perfect for me :)


274.Ashish Ranjan

February 18th, 2008 at 5:51 am

I am trying hard for days now to add and delete rows to a table. I
could really use some help…

Each row contains one button - ‘add row’ and ‘delete row’ and a text field.
When the user clicks add row within a specific cell/row, the index of
that row should be passed to a function that creates a new row using
that index (the new row should be added directly below the row where
the user clicked. The new row should contain all of the cells and html
in the cells from the row above, including the buttons/images. If a
user clicks delete row, the index of the row with the delete button
should pass to the function that deletes the row.

I would greatly appreciate any help - I’m new to this. The more
thorough the explanation, the better. I’ve seen the other postings in
this group and I can’t seem to apply the logic to my situation.

THANKS

275.Srinu

February 29th, 2008 at 5:21 am

Hi I have a doubt in javascript ,I have a table but only two colomns is there,If i’ll delete
any entire row or column but it will come order like(if i’ll delete 4 th row the 5 the row
will come 4 th place)ple help me

bye srinu

276.abi

March 7th, 2008 at 2:57 am

Hi i have a doubt in js….im creating a button dynamically on mouse over event inside the
div…but
im not able to access it(when mouse over the button)….
please help me

277.Nick

March 12th, 2008 at 2:22 am

Hi, apologies for my ignorance but I’m having a lot of trouble getting this to add text
input fields instead of paragraphs. Any suggestions please?
Thanks

278.mgwalks

March 17th, 2008 at 8:38 am

Just put the input tag in the innerHTML

279.AnnieAbey

April 3rd, 2008 at 1:29 am

Hi,
This code helped me a lot.In addition ,i want to access that textbox elements. how do we
identify a particular textbox and request.form is not working also

var ni = document.getElementById(’myDiv’);
var numi = document.getElementById(’theValue’);
var num = (document.getElementById ‘theValue’).value)+ 1;
var newdiv = document.createElement(’INPUT’);
ni.appendChild(newdivtag);

This is the code in which i have written. i want to acces the textbox .above code is
working for
how many textbox we want to display,for that it is working,but i want to acces the
txetbox and submit data into the database.

If anybody knows pls help me!!!

280.Jayanth

April 4th, 2008 at 3:30 am

Thanks very much Dustin. This article perfectly solves my requirement.

281.Oscar

April 6th, 2008 at 3:28 pm

Hi, thanks for a nice ‘n useful article. I can create a DIV, it works fine until I add some
style attributes; well exactly when I attach to my new DIV a CSS position attribute. This
is my code, and it runs fine:

wdDiv = document.createElement(’div’);
wdDiv.style.backgroundColor = ‘#FFFF00′;
wdDiv.style.height = 350 + ‘px’;
document.body.appendChild(wdDiv);
But I need an absolute positioned DIV so, when I add the new declaration, then my
previously visible DIV disappears of the screen:

wdDiv = document.createElement(’div’);
wdDiv.style.backgroundColor = ‘#FFFF00′;
wdDiv.style.height = 350 + ‘px’;
wdDiv.style.position = ‘absolute’;
document.body.appendChild(wdDiv);

Some idea?

282.Tig

April 7th, 2008 at 4:40 am

Dustin!
Great work! I am a novice at javascript and always have to refer to guys like you when
doing my projects. When I tested your removeElement function as it is:

function removeElement(divNum) {
var d = document.getElementById(’myDiv’);
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}

I could not remove the added element, but then I changed d.removeChild(olddiv); to
d.removeChild(divNum); it worked.

could you be kind enough to explian me why if you have time. Cheers

283.Sabiha Khan

May 13th, 2008 at 10:28 pm

Thank u so much this is what i was looking for…..but i remove that part from remove
function “var olddiv”……… bcoz it cause error

so i did like Mr.mdani


var d = document.getElementById(’myDiv’);
//var olddiv = document.getElementById(divNum);
d.removeChild(divNum);

Thank u so much and also


Thanks to mdani
Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScriptª is a powerful language, allowing you
to add an impressive array of dynamic functionality to otherwise static web sites. But there is
more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities,
and by applying OOP principles, best practices, and design patterns to your code, you can make
it more powerful, more efficient, and easier to work with alone or as part of a team."

• LOLcanvas
Submitted by Paul O'Shannessy
• JUNE - the JavaScript Framework
Submitted by Costin Trifan
• Track Attack
Submitted by Ray Hauge
• Simple Image Popouts
Submitted by Matt Snider
• Creating an After Effects Numerical Input
Submitted by Josh
• Using the XML DOM Without Writing 15,0000 Lines of Code
Submitted by Stephen Sorensen
• SWF Integrator
Submitted by daweed
• dsHistory Browser History Manager
Submitted by Andrew Mattie
• Forcing references/pointers to any variable in JavaScript - a simple hack
Submitted by Stephen Sorensen
• Visual JavaScript
Submitted by Ray Hauge

Submit a Prototype

All content copyright © 2003 - 2007 under the Creative Commons License. Wanna know
something? Just ask.

About | Archives | Blog Search

You might also like