提供許多欄位,讓使用者填入後,送出資料。
基本結構
<form action="#" method="#">
...
</form>
action:值是一個網址,代表要將使用者填入的資料,送至此網址。
method:送資料至 action 所指定的網址,傳送的方式基本上有 get 或 post 兩種方式。若是 get 的話,表示資料會呈現於網址當中,post 則不會出現在網址當中,相對較安全。
如果表單有要傳送檔案,需增加 enctype 屬性及其值:
<form action="#" method="#" enctype="multipart/form-data">
...
</form>
註:以上的屬性,會跟後端程式比較有關,目前可先初步認識即可。
表單相關欄位
文字框:一般文字
<input type="text" value="這是預設內容" placeholder="這是提示文字">
另可以使用 <label for="指定id"></label>
標籤,對應到欄位的 id
進行點擊的優化:
文字框:密碼
<input type="password" placeholder="請輸入密碼">
文字框:隱藏
<input type="hidden" value="123">
實際上還是存在,只是使用者看不到,而且該元素也不會佔位。
多行文字框
<textarea placeholder="提示文字">這裡是文字</textarea>
單選
基本結構,通常會搭配 <label></label>
標籤一起使用。checked
是表示預設要選取。例:
<input type="radio" value="1" checked>
<label>選項一</label>
多個選項時,若要創造單選的介面,則 name 要設定成一樣,才會被視為單選.例:
<input type="radio" name="custom_name" value="1" checked> 是
<input type="radio" name="custom_name" value="2"> 否
註:若有加上 <label>...</label>
標籤,有助於使用者的操作方便。
方式一:for 的值,對應到 id 的值。
<input type="radio" name="food_type_2" id="option1" checked>
<label for="option1">選項一</label>
方式二:<input>
放在 <label>…</label>
裡面。
<label>
<input type="radio" name="food_type_3" checked>
選項一
</label>
範例:
勾選(核取方塊)
基本結構,通常會搭配 <label></label>
標籤一起使用。checked
是表示預設要選取。例:
<input type="checkbox" value="1" checked>
<label>興趣1</label>
註:同 單選(radio)相同,若有加上 <label>...</label>
標籤,有助於使用者的操作方便。
方式一:for 的值,對應到 id 的值。
<input type="checkbox" name="food_type_2" id="option1" checked>
<label for="option1">選項一</label>
方式二:<input>
放在 <label>…</label>
裡面。
<label>
<input type="checkbox" name="food_type_3" checked>
選項一
</label>
範例:
下拉選單
基本選單:
<select name="country">
<option value="1" selected>選項1</option>
<option value="2">選項2</option>
<option value="3">選項3</option>
</select>
selected
:表示預設為這項。
分群選單,使用 <optgroup>...</optgroup>
包起來:
<select name="food">
<optgroup label="第一組">
<option value="1">選項一</option>
<option value="2">選項二</option>
</optgroup>
<optgroup label="第二組">
<option value="3">選項三</option>
<option value="4">選項四</option>
</optgroup>
</select>
在 <select>
標籤上使用 multiple 屬性可以變成多選
一般按鈕
使用 button 標籤,type 屬性設定為 "button",例:
<button type="button">這是一般按鈕</button>
這種按鈕使用者按了並不會有任何動作,需要再撰寫 JS 去開發相關需求。
資料送出按鈕
type 設定為 "submit":
<button type="submit">這是資料送出按鈕</button>
例:
使用者將這個按鈕按下去之後,會將所在的 form 表單裡的所有欄位資料,送到 form 標籤的 action 網址。
reset 按鈕
button 標籤,type 設定為 reset:
<button type="reset">這是 reset 按鈕</button>
使用者將這個 reset 按鈕按下去之後,會將所在的 form 表單裡的所有欄位資料,都清空回到預設。
file 傳遞檔案
form 標籤的 method 屬性一定要用 post 方式。
form 標籤,記得加上 enctype="multipart/form-data"
屬性。
單選語法:
多選語法:
<input type="file" multiple>
範例: