mike wrote:
If I do this:
<form name="test1">
<table>
<tr><td>
<button onClick="alert(this.form);alert(this.form.name);"> Click
Me</button>
</td></tr>
</table>
</form>
then I get [object], test1.
Yep, i am using IE. the <a> tag doesn't give me the form, but the
button does.
This is not a browser problem. The A element is a descendant of the
form, but the form is not its parent any more than your great
grandmother is one of your parents.
Form controls have a property called 'form' that refers to the form they
belong to. An A element can't be a form element and so doesn't have a
form property by default. But it can be a descendant of a form.
The script [1] below demonstrates how to find a form ancestor of any
element if there is one.
The other problem you have is trying to use the form's name to get a
reference to it. You need to use the *forms* collection:
var refToTheForm = document.forms['theForm'];
// or
var refToTheForm = document.forms.theForm;
// or (not liked)
var refToTheForm = document.theForm;
[1]
<script type="text/javascript">
function getForm(el)
{
while (el.parentNode && 'form' != el.nodeName.toLowerCase()){
el = el.parentNode;
}
if ('form' == el.nodeName.toLowerCase()) {
return el;
}
return false;
}
</script>
<form name="theForm" action="">
<table><tr><td>
<a href="#" onclick="
var x = getForm(this);
alert( (x && x.name) || 'Can\'t find the form');
return false;
">Show form element name</a>
</td></tr></table>
</form>
--
Rob