如何在HTML5中建立屬於一個或多個表單的按鈕?


HTML <button> 標籤的form屬性允許我們建立這種型別的按鈕,它適用於多個表單。可以使用此屬性指定按鈕的id,這有助於啟動表單提交或執行其他與表單相關的操作。

使用單個按鈕作為多個表單的一部分,可以避免在每個表單中重複相同的按鈕。透過將按鈕與多個表單關聯,我們可以一次處理每個表單關聯按鈕的資料。結果簡化了資料處理。屬於多個表單的按鈕可以增強使用者體驗,因為它為提交相關的表單提供了一個集中的位置。

方法一

在這個例子中,我們將建立一個屬於單個表單的提交按鈕。

演算法

  • 使用<form>標籤建立一個HTML5表單。

  • 為提交按鈕新增一些CSS樣式。

  • 使用<form>標籤建立一個表單,並設定“action”和“method”屬性。

  • 向表單元素新增一個ID屬性,其值為“newnameform”。

  • 建立一個label元素,並設定其“for”屬性的值為“newusername”。

  • 在label內,新增提示使用者輸入其新使用者名稱。

  • 建立一個input元素,並將“type”屬性設定為“text”,"id"屬性設定為“newusername”,"name"屬性設定為“newusername”。

  • 建立一個button元素,並將“type”屬性設定為“submit”,"form"屬性設定為表單的ID(“newnameform”),"value"屬性設定為“提交”。

  • 在按鈕內,新增提示使用者提交資料的文字。

示例

<!DOCTYPE html>
<html>
<head>
   <title>HTML5-form attribute</title>
   <style>
      /* Style the submit button */
      button[type="submit"] {
         font-size: 24px;
         padding: 16px 32px;
         background-color: #4CAF50;
         color: white;
         border: none;
         border-radius: 8px;
       }
   </style>
</head>
<body>
   <h1 style="color: red; font-size: 40px">Welcome back to tutorials Point</h1>
   <!-- To create a form -->
   <form action="/process_page.php" method="get" id="newnameform">
      <h3 label for="newusername">Enter your new username:</h3>
  
      <!-- get input from user in the form -->
      <input type="text" id="newusername" name="newusername" />
      <br /><br />
   </form>
   <!-- Same form id : "newnameform" is used -->
   <button type="submit" form="newnameform" value="Submit">
      Submit data
   </button>
</body>
</html>

方法二

下面的例子演示瞭如何建立一個提交多個表單的單個按鈕。

演算法

  • 設定標題。

  • 新增三個不同的表單,每個表單在body部分內都有一個唯一的ID屬性。

  • 每個表單都應該包含一個帶有“for”屬性的label和一個帶有唯一“id”屬性和“name”屬性的輸入欄位。

  • 對於第一個表單,輸入欄位的“type”屬性值為“text”。然後對於下一個表單,輸入欄位的“type”屬性值為“email”。第三個輸入欄位的“type”屬性值為“tel”。

  • 建立一個button元素,其“id”屬性為“btn1”,文字值為“提交”。

  • 向button元素新增一個“form”屬性,其值為列出所有三個表單ID(“form1 form2 form3”),以便單擊按鈕同時提交所有三個表單。

示例

<!DOCTYPE html>
<html>
<head>
   <title>Button Belonging to Forms</title>
</head>
<body>
   <!-- Form for submitting name -->
   <form id="form1">
      <label for="name">Name:</label>
      <input type="text" id="name" name="name"><br><br>
   </form>
   <!-- Form for submitting email -->
   <form id="form2">
      <label for="email">Email:</label>
      <input type="email" id="email" name="email"><br><br>
   </form>
   <!-- Form for submitting phone number -->
   <form id="form3">
      <label for="phone">Phone:</label>
      <input type="tel" id="phone" name="phone"><br><br>
   </form>
   <!-- Button for submitting all the forms -->
   <button id="btn1" form="form1 form2 form3">Submit</button>
</body>
</html>

結論

我們可以在網站的聯絡表單中使用這些型別的按鈕。這允許訪問者輕鬆地向網站所有者傳送訊息或索取資訊。在電子商務網站中,我們將使用包含使用者賬單和送貨資訊以及付款方式的表單,以及一個“提交”按鈕來完成購買。許多網站上找到的登入表單、搜尋表單和登錄檔單通常使用單個按鈕來收集多個表單。

更新於:2023年5月22日

481 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.