Determine FORM that contains a specific INPUT element?

F

Frank

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
 
M

Michael Winter

Frank said:
... 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
 
R

Richard Cornford

Frank wrote:
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.
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top