Add and Remove HTML elements dynamically with Javascript
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.

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.
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;
}
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 ;)
June 1st, 2005 at 12:12 am
Good article. Just what I was looking for!
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.
August 17th, 2005 at 7:53 am
Excelente Sr. Diaz. Muchas gracias.
August 18th, 2005 at 12:06 pm
Consider your code raped and pasted. Thank you for helping out with this great article. :)
August 18th, 2005 at 1:02 pm
I’m glad you’re making sweet love to it.
August 18th, 2005 at 11:42 pm
Thanks again for this Dustin, this is really cool
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.
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.
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
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.
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.
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);
September 9th, 2005 at 6:29 am
Thanks for your help Dustin,
now everything works.
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
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.
September 20th, 2005 at 5:04 am
Thats a really cool article, simple and sweet. A thousand thanks for that
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?
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?
September 20th, 2005 at 5:00 pm
Thanks, makes sense, but don’t you lose the ‘removeElement’ functionality?
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?
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. :)
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 ;) )
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
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?
October 19th, 2005 at 9:53 am
Sorry, to my question forward. We code I mean is:
October 22nd, 2005 at 1:15 am
Great example, i’m gonna steal it, thx!
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.
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.
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?
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
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
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 个文件ç‰å¾…上ä¼
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).
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!
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
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
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-
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
appendChildor innerHTML in that spot.Also, make sure your html string is all on one line in JavaScript. That will break your code.
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!
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.
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
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
this is from me:
tested on IE6 and FireFox 1.0.7
CMIIW :)
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
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
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
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);
}
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
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
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.
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!
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?
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.
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.
January 15th, 2006 at 10:20 pm
This is a great tip. You saved me a lot of time figuring this out. Thanks.
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.
January 31st, 2006 at 4:05 pm
Clint, this is from the Gecko DOM reference. I think it explains your dilemma.
I am in the initial stages of reseraching this– maybe if you don’t use innerHTML it would work.
February 2nd, 2006 at 7:59 am
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?
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 = "< img src=\"images/starfilled.gif\" class=\"rateimg\" onclick=\"javascript:rate("+starnum+","+articleid+")\">";
d.appendChild(objectToAppend);
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.
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
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
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*
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!
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!”; }
…
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.
March 10th, 2006 at 2:04 am
Good one.Thanks for it.I was looking for it very badly.
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
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.
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..
March 20th, 2006 at 11:39 am
If you want a good place to go for AJAX examples and tutorials, try http://ajaxpatterns.org.
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
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!
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.
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.
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.
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
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.
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
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
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
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
April 14th, 2006 at 6:50 am
me so horny at this piece o code….
i like it a laaaaaaaaat
thanks !!
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?
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?
April 19th, 2006 at 4:13 am
on click radio button we get text box using java script
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 …
April 20th, 2006 at 4:53 pm
Thanks a bunch for the tutorial. Great stuff!
April 30th, 2006 at 12:53 pm
Nice article, very helpful and it works :)
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 :)
May 9th, 2006 at 9:24 am
sorry, I would like to dynamically create a new row and column.
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..
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!
May 18th, 2006 at 2:37 am
very good
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
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.
May 25th, 2006 at 7:35 am
function removeElement(divNum) {
var d = document.getElementById(’myDiv’);
d.removeChild(divNum);
}
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);
}
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);
}
May 26th, 2006 at 6:00 am
Is there a way to use the code in a drop down menu?
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);
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
May 31st, 2006 at 9:16 am
Thanks for the great tutorial, and thanks to Chadwick for the quote solution!
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!
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?
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
June 19th, 2006 at 6:48 am
… continued
use a onload=”noDivBottomLeft()” in body tag
June 30th, 2006 at 1:04 am
Cool !!!
Using it to clean up dynamically created AJAX “windows” when closing them.
Keep them comming.
July 2nd, 2006 at 5:28 am
Very cool script! Thanks alot!
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
July 5th, 2006 at 5:01 am
Thanks a lot for it. hope its gng to work for me.
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.
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…
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…
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
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…
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..
July 14th, 2006 at 8:45 am
Thank’s, it’s a great article.
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.
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
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?
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?
July 27th, 2006 at 8:16 am
This helps me out greatly. This is very much appreciated.
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.
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
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!
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.
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?
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!
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
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
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.
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
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!
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.
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?
September 1st, 2006 at 2:05 am
Really very very usefull….
It really contain good help for managing dynamic html controls with javascript.
GREAT.
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
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.
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]
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
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 :
:-)
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?.
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.
September 18th, 2006 at 12:19 am
is it possible to remove only the elements in a div
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);
}
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.
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
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);
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
September 28th, 2006 at 5:52 am
I cant get any output with this code
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.
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
October 16th, 2006 at 3:53 am
Thanks for this.
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 !
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
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!
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
October 23rd, 2006 at 8:27 am
Great article!! It helped me… thanks, Dustin
October 26th, 2006 at 3:37 am
Thanx mate,
newdiv.innerHTML saves me. Nice tutorial dude.
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.
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.
November 2nd, 2006 at 7:14 am
Great article, very useful. Will be back here again. Thanks!
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.
November 5th, 2006 at 1:24 am
Never mind, I got it to work.
Thanks,
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,
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)
I Hope you like the code!
Donovan
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
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.
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
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 :)
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. )
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?
December 4th, 2006 at 11:17 pm
it was really very informative article. it will help me lot.thanks….
December 6th, 2006 at 6:21 am
thx so much, i decide to use this after picking many other ways ;)
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.
I thought maybe using..
would work, but I get “undefined”. Is there a way to even do that?
December 8th, 2006 at 12:08 pm
Awesome. Very helpful and simple for what I needed. Thx.
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!
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
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?
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.
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.
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
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
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:
Ps: Yes, I’m new to JavaScrit. So if I screwed it…
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
January 7th, 2007 at 9:25 pm
Thank you for the cool piece of code..its great.
January 9th, 2007 at 6:02 am
Kool stuff, really helped me a lot for dynamic content addition and removal.
Good work indeed.
Thanks
January 11th, 2007 at 1:59 am
I love java script. Thanks for the inof.
January 11th, 2007 at 12:34 pm
can any1 help me with the above code its giving me error
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.
January 18th, 2007 at 9:46 am
Oopz, here’s the code:
newdiv.innerHTML = ‘ VERWIJDER DJ new Ajax.Autocompleter(”dj[]“,”hint[]“,”autocomplete/dj.php”);’;
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); }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)
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
February 7th, 2007 at 3:58 am
awesome!just what i was looking for!!!
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?
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
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?
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.
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.
March 19th, 2007 at 7:30 am
Thanks very helpful.
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
March 26th, 2007 at 12:09 am
This is a new vision of your revove function
function removeEvent(divNum)
{
var d =