Professional Documents
Culture Documents
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.
Encoded html:
<script type="text/javascript">document.write(unescape("
"));</script>
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++
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)
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).
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.
1. Justin Perkins
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
An event is something like a hover, click, keypress, load, etc. An “event handler” is
activated when the event occurs.
3. Dustin
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.
4. Chris
5. Dave Greiner
Awesome tips, thanks so much Dustin. This will come in super handy for an upcoming
app I’m working on.
6. Samuel
7. Chris Peters
8. Dustin Diaz
9. Loic Deniel
10.Dustin Diaz
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
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
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
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
I need to remove an html input control which was not created dinamically.
15.Dustin Diaz
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
17.Sreeni.A
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?
Sreeni.A
18.Dustin Diaz
September 19th, 2005 at 10:37 am
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.
19.Amol M Vaidya
Thats a really cool article, simple and sweet. A thousand thanks for that
20.John
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
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
Thanks, makes sense, but don’t you lose the ‘removeElement’ functionality?
23.Christina
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
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
26.Hannes Baldursson
27.Tom
28.Tom
29.GeniX
30.Chris
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
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.
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
34.Dave L
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
Dear Dustin,
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
Dear Dustin,
37.Priya
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
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
40.Peter
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
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
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
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
and inside the body of my html,i have one div tag as follows
Response ;
Response ;
as
Response ; accept
Response ; reject
any luck
45.mdani
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);
}
function removeElement(divNum) {
var d = document.getElementById(’myDiv’);
d.removeChild(divNum);
}
CMIIW :)
46.Dennis
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?
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
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
Hi,
i was searching for adding an event to a dynamically created element and got to your
website.
thanks
Sravan
49.Sraan
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??
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
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
I’d like to position it and put it above the other HTML content.How can that be achieved?
Thanks
52.Scott Martin
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
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
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
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
Dustin: Thank you. Wonderful article. Used this stuff for some of the admin end of the
Timpanogos Tribune. Beautiful.
57.BBlackmoor
This is a great tip. You saved me a lot of time figuring this out. Thanks.
58.New2Arrays
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
Hi,
i was searching for adding an event to a dynamically created element and got to your
website.
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);
61.Dave Irvine
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 = "< img src=\"images/starfilled.gif\"
class=\"rateimg\"
onclick=\"javascript:rate("+starnum+","+articleid+")\">";
d.appendChild(objectToAppend);
62.Crammit
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
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
Hey Dustin great example, works nice and easily implemented to a drag and droppable
div to create dynamic workflow,
*pat*pat*pat*pat*pat*pat*pat*pat*pat*pat*
66.Jesse
67.Jesse
never mind, I figured it out. I was just blind, and didn’t see it, very simple example:
68.Guest
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.
70.suchitra
Hi,
After adding element dynamically some rows, then how can i edit those rows.
suchitra
71.Laurence
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.
72.dane
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
If you want a good place to go for AJAX examples and tutorials, try
http://ajaxpatterns.org.
74.Tony
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
“+”"+”"+”"+”";
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.
76.audienceone
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
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
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
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
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
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
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);
}
best regards,
kiril
84.Kiril Cvetkov
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
86.feanor
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){
}
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
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
89.mike
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.
ex:
… code …
… code …
… code …
90.John
91.Vetra
92.Ashley
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?
93.Ashley
94.Celsol
Great script, been looking for something like this for a few days now, big thank you to
Dustin Diaz for sharing knowledge..
95.Chris
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
very good
97.Akshay
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
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
function removeElement(divNum) {
var d = document.getElementById(’myDiv’);
d.removeChild(divNum);
}
100.Chadwick
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
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;
newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! Remove the div
“‘+divIdName+’”‘;
ni.appendChild(newdiv);
}
102.Gareth Stirling
103.Xavier
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
————————
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?
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);
———————-
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:
to:
Hope this helps anyone who finds this (It drove me nuts for over a day :) )
Mark
105.Ed
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
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
Joseph (106)
function noDivBottomLeft() {
var noStay = document.getElementById(’divStayBottomLeft’);
noStay.parentNode.removeChild(noStay);
}
then use a
109.Oliver Jackson
… continued
110.Ceejay
Cool !!!
111.Adriaan
112.Adriaan
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.
Please help!
Thanks
113.Sujit
Thanks a lot for it. hope its gng to work for me.
114.Kim Steinhaug
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
116.Kim Steinhaug
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
OK, seems the parser chopped away the code, lets do some pseudo code again :
table
form
tr
td
…
/td
/tr
/form
/table
form
table
tr
td
…
/td
/tr
/table
/form
118.Amrita
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:
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
this is just what i was looking for… Very cool script! Thanks alot. big thank you to
Dustin Diaz for sharing knowledge..
120.Ali
121.Upratovanie
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
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
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
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
126.CraigM
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.
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
128.Adriaan
129.Adriaan
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!
Sorry for the double post, but my tags was removed in the first post.
130.mike
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
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
hopefully now the code can be viewed, i took out the link tag
133.Jacob
Hi Mark,
Thanks a lot for sharing the knowlege on dynamically adding and removing html
elements.Hope you will continue the same
134.Bjarne
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
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.
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
Your article came in particularily handy for my upcoming demo at Siemans AG.
Muchas Gracias!
137.Graham B
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
Hi,
139.Paresh Prajapati
GREAT.
140.Anu
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
I would use CSS, to declare invisable state, and call it with JS:
.n‰htamatu { visibility:hidden }
142.Margus
would use CSS, to declare invisable state, and call it with JS:
[code]
.nähtamatu { visibility:hidden }
[/code]
143.Margus
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>
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
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
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
148.Nick Marinho
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
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
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.
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
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
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
154.Godfrey
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.
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”);
}
}
//======================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.
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
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
157.mihai
Hi,
I am having this prblem on IE6 with the following code:
//***********************************************************
//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
scCd.onchange = saveChanges;
Mihai
159.Salman
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)
160.John
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).
Cheers
John
161.Tvorba stránok
162.kevin
Thanx mate,
163.Matthew
164.Rob
This is a great solution. Thanks!! This cut my code by more than half and solved the
problems associated with it.
165.Keith Greer
166.Mohammed
167.Mohammed
Thanks,
168.Mohammed
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
/*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 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));
}
Donovan
170.satish
Hi ,
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
171.saurabh
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
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
I was searching for solution like this for hours and finally I’ve got it! Thanks Dustin, you
helped me :)
174.DuGiNTHaMuD
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
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
177.spiritz
thx so much, i decide to use this after picking many other ways ;)
178.Jason
newdiv.innerHTML = "";
document.frmAnalysis.TestBlah123[0]
179.George
180.Guest2#%%$&%^&#$%
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
182.Gyan
How to set background as selected of a Asp.Net2.0 TreeView node using JavaScript when
user clicks on a node?
183.sangeeth
184.Mehul
Hi…
Good tips… Thanks…
And does anyone knows answer for above question by Sangeeth. I’ve same kind
requirement too….
Thanks.
185.Ankur
thnks
186.Ankur
thnks
187.theguyofdoom
Hi,
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>
188.theguyofdoom
Ignore the
<p><a href="javascript:;"
onclick="addEvent(addEvent(document.getElementByID(’aantalmobieltjes’).value));">
Add Some Elements</a></p>
code
189.Jayaprakash
190.sudeep M
Kool stuff, really helped me a lot for dynamic content addition and removal.
Good work indeed.
Thanks
191.A to Z of World
192.Hetal
January 11th, 2007 at 12:34 pm
can any1 help me with the above code its giving me error
193.sangeeth
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
195.jb
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?
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
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+’”)
onclick=removeElement(’+divIdName+’)
(without the double quotes)
197.Ian
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
199.Nate
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
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
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
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
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
function removeEvent(divNum)
{
var d = document.getElementById(divNum).parentNode;
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
207.David
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
209.me
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.
newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! Remove the div
“‘+divIdName+’”‘;
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
hi every one
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
212.Deep
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.
213.Atul Ojha
Thanks a lot..:-)
214.dustin
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
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
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”);
216.Shaun
Never mind….
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 ….
217.raj
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
/***********************************************************************
**************************
/****************************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
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
Regards
Nate
221.kumar
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
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.
submit
thanks in advance
bye kumar
223.sarvesh
hi everybody,
i used the same code with selectboxes but when the form is posted values are not coming
224.sarvesh
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
Justin,
Have you tried putting this code inside a table? I am having major difficulties with IE and
tables…
226.mudit sharma
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));
};
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.
228.Edgars
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.
229.vinay
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;
230.ldavid20
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.
231.ldavid20
232.Luke
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
my problem is
234.Kirti
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
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
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
238.Mohamed
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
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
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.
241.Villa rentals
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
243.sirdarckcat
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/
http://jasildbg.googlepages.com/en
244.Patricia
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
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
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
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”);
tbody.appendChild(row);
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
Sevi is right! Appended elements disappear when either the forward or back buttons are
used to return to the page. Not in Firefox though.
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
250.Vivek Bajpai
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
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.
form
table
instead of
table
form
_______________________________________________________
252.drozi
253.Abhimanyu
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.
Thanks,
Abhimanyu.
254.shah
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,  etc so how i could handle this
255.Robbin
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?
256.Jon
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
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.
258.Bala Krishna
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
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
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. }
261.Giz Galor
Excellent stuff.
Got me out of a tight spot!
262.ColdFusion Developer
Thank you so much for posting this article. I used the following solution which worked
for me:
263.ador
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
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.
thanks
pavan
265.Brian
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.
266.Sree
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
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).
268.Dukacar
You can try replacing innerHTML with DOM functions but it should work with HTML
formed correctly.
269.Sathish Raja
repyl asap.
270.Bradley Hook
271.Jimmithy
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…
———-
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.
272.Jimmithy
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
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
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
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
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
279.AnnieAbey
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.
280.Jayanth
281.Oscar
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
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
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
"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.