Tuesday, December 06, 2005

Trick: Getting the Name of Enclosing Form (JS)

Here is a small Javascript function which returns the name of the enclosing form for an element. I found it quite useful in refactoring and supporting an old web application – some old JS code required a form name to access some input fields, so I created this JS snippet to be able to use the old code in a more generic way.


function getEnclosingFormName(field_name){
var obj = document.getElementById(field_name);
var node = obj.parentNode;
var i=0;
while (node.tagName !='FORM' && node !=null && node.tagName!='HTML'){
node = node.parentNode;
}
if (node.tagName == 'HTML') {
return '';
}
return node.name;
}

1 comment:

Anonymous said...

Hi Grumpy!

Thanks for sharing your tip.

I modified it for my purpose which was to actually submit the form when the user clicked on an anchor or a span dressed up to look like a button.

function submitEnclosingForm(obj) {
// Ex: submitEnclosingForm(this)
var node = obj.parentNode;
while (node.tagName !='FORM' && node !=null && node.tagName!='HTML'){
node = node.parentNode;
}
if (node.tagName == 'HTML') {
// no from found
alert('No form found in function submitEnclosingForm');
}
else {
node.submit();
}
}