if my form is similar to the layout below and i’ve captured a <input>/<select>/<textarea> element and want to capture it’s corresponding <label> element, what’s the best approach without using inline JS?
[code]
<form name=”myform”>
<label for=”email”>Email</label>
<input type=”text” name=”email”/>
<label for=”news”>Newsletter</label>
<ul>
<li><input type=”radio” name=”news” value=”yes”/>Yes</li>
<li><input type=”radio” name=”news” value=”no”/>No</li>
</ul>
</form>
note that it has to work for situations where the <label> and <input> are siblings and also when the <inputs> are children of another element (in this case a <ul>
function getLabel(obj){
var els = document.getElementsByTagName('*');
var cur=-1;
for(var i=0;i<els.length;i++){
if(els[i].nodeName=='LABEL')
cur = i;
if(els[i]==obj){
if(cur==-1)
alert('There is not label for the specified object');
else
alert(els[cur].text);
return true;
}
}
return false;
}
function getLabel(obj){
if(obj.nodeName=='BODY')
{
alert('There is no label for the specified object');
return false;
}
var cur = -1;
var pare = obj.parentNode;
var children = pare.childNodes;
for(var i=0;i<children.length;i++){
if(children[i].nodeName=='LABEL')
cur=i;
if(children[i]==obj){
if(cur==-1)
getLabel(pare);
else
{
alert('The label for the specified object is ' + children[cur].text);
return true;
}
}
}
}
To associate a label with another control [B]implicitly[/B], the control element must be within the contents of the LABEL element.
In this example, we implicitly associate two labels with two text input controls:
<FORM action="..." method="post">
<P>
<LABEL>
First Name
<INPUT type="text" name="firstname">
</LABEL>
<LABEL>
<INPUT type="text" name="lastname">
Last Name
</LABEL>
</P>
</FORM>
Note that this technique cannot be used when a table is being used for layout, with the label in one cell and its associated control in another cell.
[/QUOTE]
... By enclosing controls within their labels, you do not need the 'for' attribute, ...[/QUOTE]As [B]felgall[/B] wrote, you must use the [I]for - id [/I]association if the label is to function correctly in all browsers.
from The W3 HTML forms reference:
http://www.w3.org/TR/html4/interact/forms.html [/QUOTE]
0.1.9 — BETA 5.18