Associating Form Elements

Discussion in 'JavaScript' started by 87654321, Feb 28, 2007.

  1. #1
    Hi,

    First of all, thank you for looking at my question ;)

    I am trying to associate a form field (<input>) with a label that is not properly written. For example:

    
    <form>
    <div>
    <label>E-mail Address</label>
    </div>
    <div>
    <input type="text" name="e940" />
    </div>
    </form>
    
    Code (markup):
    What JavaScript code should I use have the script figure out that the 'E-mail address' label is referring to the the field named 'e940' with the label 'E-mail address'.

    Thanks for any help or advice.
     
    87654321, Feb 28, 2007 IP
  2. Aragorn

    Aragorn Peon

    Messages:
    1,491
    Likes Received:
    72
    Best Answers:
    1
    Trophy Points:
    0
    #2
    Is this what you are looking for?
    
    <form>
    <div>
    <label for="e940">E-mail Address</label>
    </div>
    <div>
    <input type="text" id="e940" name="e940" />
    </div>
    </form>
    
    Code (markup):
     
    Aragorn, Feb 28, 2007 IP
  3. rays

    rays Active Member

    Messages:
    563
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    58
    #3
    Aragorn

    What exactly the for='940' is there ... any advantages or disadvantages using the script ;ike this
     
    rays, Mar 5, 2007 IP
  4. Aragorn

    Aragorn Peon

    Messages:
    1,491
    Likes Received:
    72
    Best Answers:
    1
    Trophy Points:
    0
    #4
    There are two main advantages.
    1. When a user clicks on the label, the associated form element receives the focus automatically. This is really useful for radio buttons and checkboxes.
    2. You can provide shortcut keys to the form elements. This is useful for checkboxes, since it is the only method to select a checkbox using keyboard alone.
    The for attribute is used to associate an element with the label. It should hold the id of the element.
    I don't know any disadvantages of using it :)

    See the following pages for more information on labels
    http://www.siteexperts.com/tips/elements/ts17/page1.asp
    http://www.siteexperts.com/tips/elements/ts17/page2.asp
     
    Aragorn, Mar 5, 2007 IP