1. Technology

JavaScript By Example

DOM Form: 7. Creating Labelled Input Fields


For better accessibility all of the input fields in our form ought to be labelled. The label will tell the person filling out the form what to enter in that particular field. By properly defining the label we can associate the label with the form field so that it is more obvious which label goes with which form field and also allow our visitor to click on the label so as to select the corresponding field to enter a value into it.

In this example we not only create a label tag with appropriate text content and associate it with the corresponding input field but we also wrap both in a div to make styling them easier. We also check what type of input we are creating so as to place the label on the appropriate side of the input field.

var myInput;
createLInput = function(lbl,typ,nam,id) {
var newD, newL, newT, newIN;
newD = document.createElement("div");
newL = document.createElement("label");
newT = document.createTextNode(lbl);
newL.htmlFor = id;
@if (@_jscript)
newIN = document.createElement("<input name="+nam+"'>");
@else */
newIN = document.createElement("input");
newIN.name = nam;
/* @end
newIN.type = typ;
newIN.id = id;
if ('checkbox' === typ || 'radio' === typ) {
} else {
newD.appendChild(newIN); }
return newD;
myInput = createLInput('Your Email: ','text','email','email');

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Document Object Model
  7. JavaScript By Example - DOM Form: Creating Labelled Input Fields

©2014 About.com. All rights reserved.