DEV Community

Raja B
Raja B

Posted on

label and Input Tag

1.Input Tag

  • The <input> tag defines an input field where users can enter data in a form.

  • It is the most important form element in HTML.

  • <input> is a self-closing tag (it does not need a closing tag).

  • Its behavior changes based on the type attribute:

  1. type="text" → single-line text box

  2. type="password" → hidden text

  3. type="checkbox" → checkbox

4.type="radio" → radio button

5.type="email", type="number", type="date", etc.

Example:

<input type="text" name="username">
Enter fullscreen mode Exit fullscreen mode

2.Label Tag

  • The <label> tag represents a caption (text) for a form element like <input>

  • It improves accessibility: screen readers read the label when the input is focused.

  • Clicking the label text automatically focuses on the associated input field.

  • This is especially helpful for small targets like checkboxes and radio buttons.

There are two ways to connect
<label> with <input>:

Method 1: Using for and id (explicit association)

<label for="username">Username:</label>
<input type="text" id="username" name="username">
Enter fullscreen mode Exit fullscreen mode
  • for attribute in <label>must match the id of <input>

  • This explicitly binds the label to the input.

Method 2: Wrapping input inside label (implicit association)

<label>
  Username:
  <input type="text" name="username">
</label>
Enter fullscreen mode Exit fullscreen mode
  • Here, the <input> is inside the <label>, so for and id are not needed.

  • Clicking any part of the label (including the text) focuses the input.

Example:

<form>
  <label for="email">Email :</label>
  <input type="email" id="email" name="email"><br><br>

  <label for="password">Password:</label>
  <input type="password" id="password" name="password"><br><br>

  <label>
    <input type="checkbox" name="agree">
    I agree to terms 
  </label>
</form>
Enter fullscreen mode Exit fullscreen mode
  • for="email" matches id="email" → label and input are connected.

  • Checkbox uses the wrapping method (input inside label).

4. Key Points:

<input>: The field where users enter data (text, password, checkbox, radio, etc.).

<label>: The text that provides a name/description for the input; crucial for accessibility.

for and id : To connect a label with an input, the for attribute must match the id attribute (for = id).

Clicking label: Auto-focuses on the input; makes it easier to click checkboxes and radio buttons.

Screen readers: Reads the label aloud, which is highly important for accessibility.

Reference:

Top comments (0)