Dynamic creation of form elements

G

getsanjay.sharma

Hello to all Javascript programmers out there.

I have been trying to dynamically create form elements based on a
button click.

It seems as though IE has problem with setting the properties of
elements once it has been created. Also considering that "input" form
element is an empty tag i.e. doesn't have an ending tag, the
document.createElement("input") creates an element of the form
<input ...> without an ending "/". Creating a form element dynamically
in a cross browser compatible manner seems to be a herculean task.

Here is my failed attempt at it:

<html>
<head>
<script type="text/javascript">
COUNTER = 0;

function createText(parentId)
{
var frmElement = document.getElementById(parentId);
var nameId = "txt" + COUNTER++;
if(document.all) //IE
{
var elem = document.createElement("<input type = 'text' name='" +
nameId +"' id='" + nameId + "' \/>");
}
else
{
var elem = document.createElement("input");
elem.type = "text";
elem.id = elem.name = nameId;
}
var br = document.createElement("br");
frmElement.appendChild(elem);
alert(document.getElementById('body').innerHTML); //dump the
generated html
elem.appendChild(br);
}
</script>
<body id="body">
<form action="#" id="frm">
<input type="button" value="Create" id="btn" name="btn" onmouseover =
"this.style.fontSize = '120px'; " onclick="createText('frm');" /><br /</form>
</body>
</html>

Any kind of snippet / links / other help on this topic would be highly
appreciated.

Thanks and regards,
STS
 
T

Thomas 'PointedEars' Lahn

I have been trying to dynamically create form elements based on a
button click.

It seems as though IE has problem with setting the properties of
elements once it has been created. Also considering that "input" form
element is an empty tag

No, it is an element with an empty content model. An empty tag looks like
i.e. doesn't have an ending tag,

Wrong, its end tag is merely optional in HTML:

http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT

| <!ELEMENT INPUT - O EMPTY -- form control -->
^

(It isn't optional in XHTML because of XML-wellformedness, hence <input
the document.createElement("input") creates an element of the form
<input ...> without an ending "/".

Congratulations, you have just discovered the difference between tag-soup
HTML and well-formatted X(HT)ML.
Creating a form element dynamically in a cross browser compatible manner
seems to be a herculean task.

Not at all.
Here is my failed attempt at it:

<html>

Not Valid, the DOCTYPE declaration is missing before this tag.
<head>
<script type="text/javascript">
COUNTER = 0;

Variables must be declared or they are only properties of an object in
the scope chain. `COUNTER' is obviously not a constant, therefore the
all-capital identifier is misleading bad style.
function createText(parentId)
{
var frmElement = document.getElementById(parentId);
var nameId = "txt" + COUNTER++;
if(document.all) //IE
http://PointedEars.de/scripts/test/whatami#inference

{
var elem = document.createElement("<input type = 'text' name='" +
nameId +"' id='" + nameId + "' \/>");

First, there is no need to escape every occurence of `/' in a string
literal. That character only needs to be escaped when it is part of a
script within a HTML `script' element and is preceded by `<', thus forming
the SGML ETAGO (End TAG Open) delimiter sequence `</' which ends CDATA content.

Second, as you generate HTML, what you generate then is equal to

<input ...>&gt;

because in HTML SHORTTAG syntax the `/' within a start tag ends that tag
(but not that element -- you see?). It is only that few user agents support
that feature (properly), and the other UAs remove or ignore it as part of
error-correction. Simply don't use it.
}
else
{
var elem = document.createElement("input");
elem.type = "text";
elem.id = elem.name = nameId;
}

Try this instead:

var elem = document.createElement(
"<input type='text' name='" + nameId +"' id='" + nameId + "'>");

if (!elem)
{
elem = document.createElement("input");
// ...
}
Any kind of snippet / links / other help on this topic would be highly
appreciated.

Other people here have suggested other solutions before.

Google is your friend. [psf 6.1]


PointedEars
 
R

RobG

IE has difficulty with the name attribute. If you don't need script
access to the name attribute of form controls, it isn't a problem as
the name will be used when the form is submitted, you just can't use
it as a reference to the control.

However, if you want to use the name, say to serialise the form for an
AJAX request or to reference the control, you need to deal with it.

No, it is an element with an empty content model. An empty tag looks like


Wrong, its end tag is merely optional in HTML:

Not optional, forbidden:

<URL: http://www.w3.org/TR/html401/interact/forms.html#h-17.4 >
 
D

David Mark

Hello to all Javascript programmers out there.

I have been trying to dynamically create form elements based on a
button click.

It seems as though IE has problem with setting the properties of
elements once it has been created. Also considering

It has some quirks when creating input elements.

[snip]
Here is my failed attempt at it:

As mentioned, you need a doctype.
<html>
<head>
<script type="text/javascript">
COUNTER = 0;

function createText(parentId)
{
var frmElement = document.getElementById(parentId);
var nameId = "txt" + COUNTER++;
if(document.all) //IE

This is nonsense. You are inferring IE from document.all, but other
browsers support document.all.
{
var elem = document.createElement("<input type = 'text' name='" +
nameId +"' id='" + nameId + "' \/>");
}

And this is clearly non-standard IE-only script.
else
{
var elem = document.createElement("input");
elem.type = "text";

Why are you setting the type property at all? The default is text.
elem.id = elem.name = nameId;
}
var br = document.createElement("br");
frmElement.appendChild(elem);
alert(document.getElementById('body').innerHTML); //dump the
generated html
elem.appendChild(br);

This is clearly wrong as elem is the newly appended input element.
}
</script>
<body id="body">
<form action="#" id="frm">
<input type="button" value="Create" id="btn" name="btn" onmouseover =
"this.style.fontSize = '120px'; " onclick="createText('frm');" /><br /

Is this supposed to be an XHTML document?
</form>
</body>
</html>

Any kind of snippet / links / other help on this topic would be highly
appreciated.

Try this:

var counter = 0;
function createText(parentId)
{
var frmElement = document.getElementById(parentId);
var nameId = "txt" + counter++;
var elem = document.createElement("input");
frmElement.appendChild(elem);
elem.id = elem.name = nameId;
var br = document.createElement("br");
frmElement.appendChild(br);
alert(frmElement.elements['txt0']);
}
 
P

Peter Michaux

IE has difficulty with the name attribute. If you don't need script
access to the name attribute of form controls, it isn't a problem as
the name will be used when the form is submitted, you just can't use
it as a reference to the control.

However, if you want to use the name, say to serialise the form for an
AJAX request or to reference the control, you need to deal with it.


I wanted a generic DOM element builder function and goofed around with
all the problems using createElement. IE has problems when there is a
name attribute and frameborder attribute is not respected in some
browsers.

I now believe innerHTML is far more standardized than using
createElement and setting attributes. By "standardized" I mean more
browsers support it in the same way which is more important than some
governing body.

Anyway now I'm using a function that goes something like this

build(tag, attributes) {
attributes = attributes || {};

var attrs = [];
for (var p in attributes) {
attrs.push(' '+(p=='className'?'class':p)+
'="'+attributes[p]+'"');
}

var html = '<' + tagName + attrs.join('') + '>';

var p = document.createElement('div');
p.innerHTML = html;
return p.childNodes[0];
}

The above is just a trimmed down version of what I use for posting
here. I didn't test this. In the real version special care needs to be
taken when creating table and option elements.

Peter
 
T

Thomas 'PointedEars' Lahn

RobG said:

How can something be forbidden and be Valid HTML that is explicitly allowed
as being optional by the DTDs (even HTML 4.01 Strict)? Clearly that is an
error in the prose of the specification. It is much more an error
considering that XHTML 1.0 allows for HTML-compatible XHTML. XHTML 1.0
could never be made HTML 4.01-compatible if all those close tags marked as
forbidden by the prose of the HTML 4.01 Specification (but allowed by the
HTML 4.01 DTDs) could not be used.


PointedEars
 
R

RobG

Thomas said:
How can something be forbidden and be Valid HTML that is explicitly allowed
as being optional by the DTDs (even HTML 4.01 Strict)?

Because HTML is defined first and foremost by the specification - the
DTD is a machine-compatible version of the specification. Where the two
differ, the prose of the specification must take precedence. There are
many nuances within the specification that can't be addressed by a DTD,
to quote the self-confessed HTML pedant Jukka Korpela:

"...the prose part of the HTML specification is normative, except where
explicitly flagged as non-normative. What else would be the very point
of a specification? (By the way, even the requirement that HTML
documents must comply with the syntax defined in the DTDs must be given
in prose, ultimately. So without the prose, the DTDs have no normative
role.) "

<URL:
http://groups.google.com.au/group/c...t&q=HTML+4+DTD+specification#551a3c3e69fae827
Clearly that is an
error in the prose of the specification.

Not at all, it is an example of a DTD being incapable of representing
all the rules in the HTML Specification.

It is much more an error
considering that XHTML 1.0 allows for HTML-compatible XHTML. XHTML 1.0
could never be made HTML 4.01-compatible if all those close tags marked as
forbidden by the prose of the HTML 4.01 Specification (but allowed by the
HTML 4.01 DTDs) could not be used.

No, it isn't. It is possible to serve XHTML as HTML only because
browsers are forgiving of HTML markup. The reverse is not possible as
user agents are expressly forbidden to be forgiving of XML markup
(although many are anyway in some respects). The fact that browsers
tolerate invalid HTML markup does not make the markup conforming to the
specification.

Anyhow this discussion would be much better had in
comp.infosystems.www.authoring.html, where there are contributors who
are much more expert in HTML that I could ever hope to be.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,069
Latest member
SimplyleanKetoReviews

Latest Threads

Top