Dynamically create form using Javascript

SONYFX

Senior member
May 14, 2003
403
0
0

I am developing a part of my website that require a dynamic creation of forms (Just like in gmail.com when clicking the "attach another file" link) but the problem is, i dont know how to do it using javascript. Can anyone provide me a code that can do such thing. Thanks.
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
The brute force way would be to generate the html string in javascript:

var formhtml = "<form method='POST' ....";
if (foo) {
..formhtml += "...";
} else {
..formhtml += "...";
}

Then you can do a document.write(formhtml) if you're in the right spot, or locate the correct container tag (like a div with a certain id) and set it's innerhtml to your formhtml.

Potentially, you could also generate the forms server-side and insert them into your page in a variety of different ways like an iframe or ajax.
 

dukdukgoos

Golden Member
Dec 1, 1999
1,319
0
76
The above method is kinda "old school". The more modern and extensible way is to use the Document Object Model (DOM) to create the form. Read about it here.
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
I'll be the first to admit that I'm not an expert at this stuff :) If there's more modern and standards compliant ways of doing it on that site then, by all means...

(Although I do find it kind of humorous that the main page of quirksmode.org uses document.write() to set up, of all things, frames :p)
 

dukdukgoos

Golden Member
Dec 1, 1999
1,319
0
76
Originally posted by: kamper
I'll be the first to admit that I'm not an expert at this stuff :) If there's more modern and standards compliant ways of doing it on that site then, by all means...

(Although I do find it kind of humorous that the main page of quirksmode.org uses document.write() to set up, of all things, frames :p)

Heh, never noticed that before :) It's still a good site about how to do DOM stuff correctly, even if the site itself isn't the greatest (I hate the frame setup).