Master HTML Forms: Elements, Attributes, and Practical Code Examples

This guide explains HTML form elements, common attributes like readonly, disabled, and required, and demonstrates how to build functional forms with code snippets, including input types, labels, and form association techniques for effective data submission.

Lin is Dream
Lin is Dream
Lin is Dream
Master HTML Forms: Elements, Attributes, and Practical Code Examples

1. Form Elements

Forms are commonly used for login, data entry, and other interactions. The action attribute specifies the file or script that processes the form (default is the current page), and the method attribute determines the HTTP method, either GET or POST.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
<form action="#" method="post">
  <p>文本域<textarea rows="5" cols="5" maxlength="50"></textarea></p>
  <p>选择文件 <input type="file" name="" id="" value="" /></p>
  <!--以下为HTML5新增输入属性-->
  <p>选择日期<input type="date" /></p>
  <p>选择月份和年份<input type="month" /></p>
  <p>填入数字<input type="number" min="1" max="10" /></p>
  <p>选择颜色<input type="color"></p>
  <p>可控滑块<input type="range" min="0" max="30" /></p>
  <p>邮件<input type="email" /><p/>
</form>
</body>
</html>

2. Form Attributes

readonly="readonly" : makes the field read‑only, preventing edits.

disabled="disabled" : disables the control so it cannot be used.

placeholder="..." : shows hint text inside the input.

required="required" : forces the field to be filled before submission.

title="..." : displays a tooltip when the mouse hovers over the element.

pattern="[A‑z]{3}" : uses a regular expression to restrict input format (see https://regexper.com/ for visual regex tools).

To improve usability, you can associate a <label> with a control using the for attribute that matches the control's id. The form attribute on a label can reference a form's id, allowing the label to activate the control even when placed outside the form.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form action="#" method="post" id="myform">
        <p><label>男<input type="radio" checked="checked" name="gender" id="men" /></label></p>
        <p><label for="women">女<input type="radio" name="gender" id="women" /></label></p>
    </form>
    <label for="women" form="myform">点击选择女</label>
</body>
</html>

For a complete list of <input> attributes, refer to the W3Schools documentation: https://www.w3school.com.cn/tags/tag_input.asp

frontendWeb developmentcode examplesHTMLFormsAttributes
Lin is Dream
Written by

Lin is Dream

Sharing Java developer knowledge, practical articles, and continuous insights into computer engineering.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.