Entry
How can I access the LABEL text for a INPUT field with DOM methods?
How can I access the LABEL text for a INPUT field with DOM methods?
Feb 14th, 2000 07:40
Martin Honnen,
HMTL 4 introduces the
<LABEL FOR="elementId">
element which displays the content of the LABEL element in association
with the named FORM element.
There are no DOM methods to find the LABEL element associated with a
particular INPUT field but with a simple search through
document.getElementsByTagName('LABEL')
you achieve it:
<HTML>
<HEAD>
<SCRIPT>
function findLabelFor (elOrId) {
var el = typeof elOrId == 'string' ? document.getElementById(elOrId) :
elOrId;
var labels = document.getElementsByTagName('LABEL');
var found = false;
for (var l = 0; l < labels.length; l++)
if (found = el.id == labels[l].htmlFor)
break;
if (found)
return labels[l];
else
return null;
}
function findLabelTextFor (elOrId) {
return findLabelFor(elOrId).firstChild.nodeValue;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="aForm">
<LABEL FOR="god">
God
</LABEL>
<INPUT TYPE="text" ID="god" NAME="god"
ONBLUR="if (this.value == '') alert(findLabelTextFor(this));"
>
<BR>
<LABEL FOR="religion">
Religion
</LABEL>
<INPUT TYPE="text" ID="religion" NAME="religion"
ONBLUR="if (this.value == '') alert(findLabelTextFor(this));"
>
</FORM>
</BODY>
</HTML>