faqts : Computers : Programming : Languages : JavaScript : Forms : Labels

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

36 of 56 people (64%) answered Yes
Recently 7 of 10 people (70%) answered Yes

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>