Click to See Complete Forum and Search --> : Adding label to form


mike_p
06-12-2004, 11:57 AM
How can I add some label element into the form?
This code doesn´t work:

<script>
function add() {
var x=document.createElement("label");
x.setAttribute("class","lab");
var t=document.createTextNode("Text: ");
x.appendChild(t);
f=document.forms[0].elements[2];
document.forms[0].insertBefore(x,f);
}
</script>
<form onsubmit="add()">
<fieldset>
<legend>Some legend</legend>
<label>Name </label><input type="text" />
<label>Surname </label><input type="text" />
<label>Age </label><input type="text" />
<input type="submit" value="Submit" />
</fieldset>
</form>
How can I add some label element into the form?

CyCo
06-12-2004, 01:26 PM
Example.

<LABEL for="firstname">First name:
<INPUT type="text" id="firstname" tabindex="1">
</LABEL>

See:
http://www.w3.org/TR/WCAG10-HTML-TECHS/#forms-labels

David Harrison
06-12-2004, 02:45 PM
You don't neccessarily need to put the input inside the label, but you are supposed to have an explicit link to the form element by using the for and id attributes.<label for="input1">Name:</label>
<input type="text" id="input1" />However that's not what the OP was asking about.

I think that the problem was the way you were applying the class attribute to the label. Labels are only for form elements though, (input and select).<script type="text/javascript">//<![CDATA[

function add() {

var x=document.createElement("label");
x.class="lab";
x.for="some_field"
x.appendChild(document.createTextNode("Text: "));

document.forms[0].insertBefore(x,document.forms[0].elements[2]);

}

//]]></script>