1. 程式人生 > 實用技巧 >html——表單

html——表單

插入表單物件

網頁中的表單由許多不同的表單元素組成,這些表單元素包括文字欄位、單選按鈕、複選框、按鈕等。

文字欄位

在網頁中最常見的表單元素就是文字欄位,使用者可以在文字欄位內輸入字元或者單行文字。 語法:

<input
  type="text"
  name="控制元件名稱"
  value="文字欄位的預設取值"
  size="控制元件的長度"
  maxlength="最長字元數"
/>

該語法包含了許多引數,除了 type 引數以外,其他的引數都是可選的,大家可以自行選擇。舉個例子:

<form name="formBox" method="post" action="">
  姓名:<input type="text" name="name" size="20" /><br />
  年齡:<input type="text" name="age" size="40" value="10" maxlength="3" />
</form>

可以嘗試給年齡輸入值,如果文字欄位長度超過了 3,就不能再輸入了。

密碼輸入框

密碼輸入框是一種特殊的文字欄位,他的各個屬性和文字欄位是相同的,但是輸入進密碼輸入框的字元全部是“*”表示,保證周圍人看不見輸入的文字。

<input type="password" name="pwd" />

單選按鈕

單選按鈕可以使使用者從選擇列表中選擇一個選項。

<form name="formBox" method="post" action="">
  <input type="radio" name="sex" value="male" checked />男<br />
  <input type="radio" name="sex" value="female" />女
</form>

幾個單選按鈕可以連線在一起,只需要把它們的 name 值設定為相同的。同一組中只有一個按鈕可以同時被選。如果沒有選中任何一個,那麼整個單選按鈕池就被認為處於未知狀態,且不會隨表單提交。 可以嘗試如果 name 不相同或者沒有 name 會是什麼情況。

複選框

複選框可以讓使用者從一個選項列表中選擇超出一個的選項。

<form name="formBox" method="post" action="">
  <input type="checkbox" name="music" checked />音樂<br />
  <input type="checkbox" name="art" />美術<br />
  <input type="checkbox" name="math" />數學<br />
</form>

複選框可以擁有自己的名字,並不需要屬於一個組。

按鈕

HTML 表單中,有三種按鈕:提交按鈕,重置按鈕,匿名按鈕。我們可以使用 <button> 元素或者 <input> 元素來建立一個按鈕。type 屬性的值指定顯示什麼型別的按鈕。

提交按鈕(submit)

用於傳送表單資料給伺服器。

語法:

<form name="formBox" method="post" action="">
  <input type="text" value="輸入的內容" />
  <button type="submit">
    This a submit button
  </button>

  <!--or-->

  <input type="submit" value="This is a submit button" />
</form>

重置按鈕(reset)

重置按鈕用來清除使用者在頁面中輸入的資訊。

語法:

<form name="formBox" method="post" action="">
  <input type="text" />
  <button type="reset">
    This a reset button
  </button>

  <!--or-->

  <input type="reset" value="This is a reset button" />
</form>

在文字框中輸入內容,點選按鈕即可清除。

匿名按鈕(button)

沒有自動生效的按鈕,但是可以使用 JavaScript 程式碼進行定製。如果你省略了 type 屬性,那麼這就是預設值。

語法:

<button type="button">
  This a anonymous button
</button>

<!--or-->
<button>
  This a anonymous button
</button>

<!--or-->
<input type="button" value="This is a anonymous button" />

不管使用的是 <button> 元素還是 <input> 元素,按鈕的行為都是一樣的。它們的不同點在於:

  • 從前面的例子中也可以看出 <button> 元素允許你使用 HTML 內容作為其標記內容,但 <input> 元素只接受純文字內容。
  • 使用 <button> 元素,可以有一個不同於按鈕標籤的值(通過將其設定為 value 屬性)。(但是在 IE 8 之前的版本中是不行的)。