表單的基本結構
<form action="/index.php" method="get">
<p>用戶名:<input type="text" name="username"></p>
<p>密碼:<input type="password" name="password"></p>
<textarea cols="30" rows="10"></textarea>
<p><button type="submit">提交</button></p>
</form>
表單使用一個form
標簽。它有兩個屬性分別是action
和method
。
action
的作用是當用戶提交表單后,將表單中的數據提交到一個后臺鏈接(服務器),由這個鏈接(如php,python等后臺)來處理這些數據。
method
:提交用戶的數據由兩種方式,分別是get
和post
。
input標簽
:標簽用于搜集用戶信息。
根據不同的 type
屬性值,輸入字段擁有很多種形式。輸入字段可以是文本字段、復選框、掩碼后的文本控件、單選按鈕、按鈕等等。
type
的值有很多:
text
:輸入框
password
:密碼輸入框
button
:按鈕
submit
:提交按鈕
checkbox
:多選框
radio
:單選框
number
:數字
email
:郵件(有校驗功能)
date
:日期
等。
input
中的name
屬性:
用戶在輸入框輸入的數據,后臺如何拿到?就可以根據這個name
屬性的值來定位到該input
后取出其中的數據。如在php
中,可以使用如下方法來獲取username
和password
:
$username = $_GET['username'];
$password = $_GET['password'];
input
中的value
屬性:
給輸入框設置一個value值,不設置的話輸入框為空,否則會顯示value
中的屬性值。
input
中的placeholder
屬性:輸入框提示。
<input type="text" placeholder="請輸入用戶名" />
<textarea cols="30" rows="10"></textarea>
:文本域,cols
和rows
分別為列數和行數。
<form action="">
<div>
性別:
<input type="radio" name="gender" id="male">
<label for="male">Male</label>
<input type="radio" name="gender" id="female">
<label for="female">Female</label>
</div>
<div>
愛好:
<input type="checkbox" id="basketball">
<label for="basketball">籃球</label>
<input type="checkbox" id="football">
<label for="football">足球</label>
<input type="checkbox" id="swim">
<label for="swim">游泳</label>
</div>
<div>
選擇:
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
</form>
radio
表示單選框,但是只有在其name
屬性相同的情況下,幾個單選框才能選擇其中一個,否則沒有設置好相同的name
值,那么就可以選擇多個單選框,就是去了其本意。
checkbox
表示多選框,用戶可以選擇多個選項。
<label>
,一種文本標簽,它有一個屬性for
,這個屬性對應的是radio
或者checkbox
的id
值。如此設置以后,只要點擊label
的文本部分,就可以選擇radio
或者checkbox
了。否則,必須要點擊radio
的圓圈圈或者checkbox
的方格才能選中,選擇區域過小。
select
:下拉選擇框,其子元素option
表示下拉菜單的項。
表單設計原則
- 幫助用戶不出錯
- 盡早提示錯誤
- 擴大選擇/點擊區域
- 控件較多時要分組
- 主要動作和次要動作