iT邦幫忙

2025 iThome 鐵人賽

DAY 10
0

學習目標

  • 熟悉更多表單輸入型態:radiocheckboxselectfile
  • 學會分組:使用 <fieldset><legend>
  • 能建立多選、單選與下拉選單
  • 理解表單送出與資料格式化的基本觀念
  • 嘗試做一份「註冊表單」

重點觀念(互動再升級)

  • 單選與複選radio 用於單選,必須共享同一個 namecheckbox 可多選。
  • 下拉選單<select> 搭配 <option>,適合選項較多的情況。
  • 檔案上傳<input type="file">,讓使用者上傳檔案。
  • 群組化:使用 <fieldset><legend>,讓表單更有結構。

表單進階示範

<body>
  <h1>註冊表單</h1>
  <form action="/register" method="post">
    <fieldset>
      <legend>基本資料</legend>
      <label for="username">使用者名稱:</label>
      <input type="text" id="username" name="username" required><br><br>

      <label for="password">密碼:</label>
      <input type="password" d="password" name="password" required><br><br>

      <label>性別:</label>
      <input type="radio" id="male" name="gender" value="male">
      <label for="male">男</label>
      <input type="radio" id="female" name="gender" value="female">
      <label for="female">女</label><br><br>

      <label>興趣:</label>
      <input type="checkbox" id="coding" name="hobby" value="coding">
      <label for="coding">寫程式</label>
      <input type="checkbox" id="music" name="hobby" value="music">
      <label for="music">音樂</label>
      <input type="checkbox" id="sport" name="hobby" value="sport">
      <label for="sport">運動</label><br><br>

      <label for="country">國家:</label>
      <select id="country" name="country">
        <option value="tw">台灣</option>
        <option value="jp">日本</option>
        <option value="us">美國</option>
      </select><br><br>

      <label for="avatar">上傳大頭貼:</label>
      <input type="file" id="avatar" name="avatar"><br><br>
    </fieldset>

    <button type="submit">送出</button>
  </form>
</body>

image

常見錯誤與修正

  • radio 沒有同名 name → ✅ 加上相同 name 才能單選
  • checkbox 當單選用 → ✅ checkbox 適合多選,單選請用 radio
  • ❌ 下拉選單忘記加 <option>value → ✅ 加上 value 才能傳送資料
  • ❌ 表單過於雜亂 → ✅ 使用 <fieldset><legend> 區分區塊

今日小挑戰(可交付)

  • [ ] 建立一個性別單選 radio
  • [ ] 建立一個興趣複選 checkbox
  • [ ] 建立一個國家選擇的下拉清單
  • [ ] 新增一個檔案上傳欄位
  • [ ] 使用 <fieldset> 包住表單區塊

DAY10 心得

今天學到的進階表單元素讓我覺得表單世界真的很強大。以前只會用文字輸入框,但實際上 radiocheckboxselect 都能讓互動變得更直覺。尤其是 radio 的同名 name 限制,讓我理解瀏覽器是怎麼判斷「單選群組」的。

在練習中,我嘗試組合多種欄位做一份小型註冊表單,發現使用 <fieldset><legend> 可以讓整個表單更有架構,看起來也更專業。這些元素其實都不複雜,但放在一起卻能打造完整的互動介面。

我覺得這個階段的 HTML 開始真正往「使用者輸入」靠攏,網站也因此更貼近真實應用。接下來應該就能把前幾天學到的排版技巧結合起來,讓整個表單更美觀。


上一篇
Day 9 - 表單的魔法
下一篇
Day 11 - 表單驗證與使用者體驗
系列文
程式煉金術:Bug退散!前端驅魔記14
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言