By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,836 Members | 2,059 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,836 IT Pros & Developers. It's quick & easy.

Determine FORM that contains a specific INPUT element?

P: n/a
I created this test routine to return the form containing a certain
input element:

function GetElementForm(element)
{
// Return the form that contains element.

var myElement = element;

while (myElement)
{
myElement = myElement.parentNode;
if (myElement)
{
var sTagName = myElement.tagName;
if (sTagName)
{
if (sTagName.toLowerCase() == "form")
{
break;
}
}
}
}
return myElement;
}

This seems to work for "well formed" HTML, but fails for example, when
a form is defined within a table.

Is there a technique that works reliably?

Thanks,

Frank

Oct 11 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Frank wrote:
... return the form containing a certain input element:
[snip]
Is there a technique that works reliably?
formElement.form

The property, form, is defined for all form controls (button, fieldset,
input, label, legend, object, option, select, textarea). If the controls
is a descendant of a form, the property will refer to that object - it
is null, otherwise.

Mike
Oct 11 '06 #2

P: n/a
Frank wrote:
<snip>
This seems to work for "well formed" HTML, but
fails for example, when a form is defined within
a table.
That is not true. A form can be defined within a table (specifically,
contained within a single TD or TH element) and the chain of parent nodes
of its form controls will include its form ancestor.

Generally, if you want to use a table to 'lay-out' form controls (a
reasonable thing to do in semantic HTML as forms can be tabular) you
would wrap the Form elements around the TABLE, and so (potentially) have
structurally valid HTML to start with.
Is there a technique that works reliably?
You could try following the general advice that if a document is to be
scripted it should always be a structurally valid document to start with.
Doing that completely avoids all the consequences of inconsistent and
unexpected DOM structures that result form browser error correction in
tag-soup documents. (That is; don't make things difficult for yourself
when a simple (potentially mechanised) quality check on the HTML can
eliminate many issues at a stroke).

Richard.
Oct 11 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.