HTML 表單用于搜集不同類型的用戶輸入。
HTML 表單元素指的是不同類型的 input 元素、復選框、單選按鈕、提交按鈕等。
<input>
元素是最重要的表單元素。<input>
元素有很多形態,根據不同的 type 屬性。
1、文本輸入
<input type="text">
定義用于文本輸入的單行輸入字段:
<html>
<body>
<form>
First name:<br />
<input type="text" name="firstname"><br />
Last name:<br />
<input type="text" name="lastname">
</form>
<p>Note that the form itself is not visible.</p>
<p>Also note that the default width of a text field is 20 characters.</p>
</body>
</html>
2、單選按鈕輸入
<input type="radio">
定義單選按鈕。
<html>
<body>
<form>
<input type="radio" name="sex" value="male">Male<br />
<input type="radio" name="sex" value="female" checked>Female
</form>
</body>
</html>
3、提交按鈕
<input type="submit">
定義用于向表單處理程序提交表單的按鈕。
表單處理程序在表單的 action 屬性中指定:
<html>
<body>
<form action="action_page.php">
First name:<br />
<input type="text" name="firstname" value="Mickey"><br />
<input type="text" name="lastname" value="Mouse"><br />
<input type="submit" value="Submit">
</form>
<p>If you click "Submit", the form-data will be sent to a page called "action_page.php".</p>
</body>
</html>
- Action 屬性
action 屬性定義在提交表單時執行的動作。
通常,表單會被提交到 web 服務器上的網頁。
如果省略 action 屬性,則 action 會被設置為當前頁面。
<form action="action_page.php">
- Method 屬性
method 屬性規定在提交表單時所用的 HTTP 方法(GET 或 POST):
<form action="action_page.php" method="GET">
- Name 屬性
如果要正確的被提交,每個輸入字段必須設置一個 name 屬性。
以下實例只會提交 "lastname" 輸入字段。
<form action="action_page.php">
First name:<br />
<input type="text" value="Mickey"><br />
Last name:<br />
<input type="text" name="lastname" value="Mouse"><br />
<input type="submit" value="Submit">
</ form>
4、用 <fieldset>
組合表單數據
<fieldset>
元素組合表單中的相關數據。
<legend>
元素為 <fieldset>
元素定義標題。
<html>
<body>
<form action="action_page.php">
<fieldset>
<legend>Personal information:</legend>
First name:<br />
<input type="text" name="firstname" value="Mickey"><br />
Last name:<br />
<input type="text" name="lastname" value="Mouse"><br />
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
</html>