在 HTML 中为表单控件添加标签?


在 HTML 中,<label> 标签用于为像 <input>、<progress>、<select>、<meter>、<textarea> 这样的一些元素定义标签。

<input type="checkbox">
<input type="color">
<input type="date">
<input type="datetime-local">
<input type="email">
<input type="file">
<input type="month">
<input type="number">
<input type="password">
<input type="radio">
<input type="range">
<input type="search">
<input type="tel">
<input type="text">
<input type="time">
<input type="url">
<input type="week">
<meter>
<progress>
<select>
<textarea>

语法

下面是 HTML 中 <label> 标签的用法 −

<label> form content... </label>

这个 <label> 标签使用 for 和 form 属性,现在让我们看看 for 和 form 属性的值和描述。

  • for − 为标签关联的表单元素指定 id。下面是标签中 for 属性的语法 -

<label for=”element_id”>
  • form − 使用该属性时,有多个表单,且它指定这个标签属于哪个表单。将值设为 form_id,下面是标签中 form 属性的语法 -

<label form="form_id">

示例

在以下示例中,我们创建了一个表单,并在其中为控件添加了标签。

<!DOCTYPE html>
<html>
<body>
   <h1>Welcome to TutorialsPoint</h1>
   <h2>The label for attribute</h2>
   <p>Click on one of the radio button:</p>
   <form action="/action_page.php">
      <input type="radio" id="html" name="language" value="HTML">
      <label for="html">HTML</label>
      <br>
      <input type="radio" id="css" name="language" value="CSS">
      <label for="css">CSS</label>
      <br>
      <input type="radio" id="javascript" name="language" value="JavaScript">
      <label for="javascript">JavaScript</label>
      <br>
      <br>
      <input type="submit" value="Submit">
   </form>
</body>
</html>

示例

让我们看另一个示例 −

<!DOCTYPE html>
<html>
<body>
   <h1>Welcome to TutorialsPoint</h1>
   <h2>The label for form attribute</h2>
   <p>The label in the second radio button is outside the form, but still a part of the form. Try to click the "Teacher" text label to select the "Teacher" radio button.</p>
   <form action="/action_page.php" id="form1">
      <input type="radio" id="student" name="person" value="STUDENT">
      <label for="student">STUDENT</label>
      <br>
      <input type="radio" id="teacher" name="person" value="TEACHER">
      <br>
      <input type="radio" id="admin" name="person" value="ADMIN">
      <label for="admin">ADMIN</label>
      <br>
      <br>
      <input type="submit" value="Submit">
   </form>
   <br>
   <label form="form1" for="teacher">TEACHER</label>
</body>
</html>

示例

在此示例中,我们尝试创建一个示例登录页面并向其中添加标签。

<!DOCTYPE html>
<html>
<head>
   <title>HTML label Tag</title>
</head>
<body>
   <label for="email">EMAIL-ID: <br />
   <input type="email" value="" name="emailid" size="30" placeholder="Enter a valid email address">
   <br />
   <br />
   <label for="phone">PHONE NO: <br />
   <input type="text" value="" name="phno" size="30" maxlength="10" placeholder="Enter a valid phone number" pattern="[0-9]{10}">
   <br />
   <br />
</body>
</html>

修改于:10-Oct-2023

386 浏览量

开启您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.