如何在 HTML5 中创建属于一个或多个表单的按钮?

html5front end technologyweb development更新于 2024/7/20 6:36:17

HTML <button> 标签的 form 属性允许我们创建适用于多个表单的此类按钮。可以使用此属性指定按钮的 ID,这有助于启动表单提交或执行其他与表单相关的操作。

使用属于多个表单的单个按钮可以避免在每个表单中重复使用相同的按钮。通过将一个按钮与多个表单关联,我们可以一次性处理每个表单关联按钮的数据。因此,数据处理变得更加简单。将按钮作为多个表单的一部分可以增强用户体验,因为它为相关表单的提交提供了一个集中的位置。

方法 - 1

在此示例中,我们将创建一个属于单个表单的提交按钮。

算法

  • 使用 <form> 标签创建一个 HTML5 表单。

  • 为提交按钮添加一些 CSS 样式。

  • 使用 <form> 标签创建一个表单,并带有属性"action"和"method"。

  • 为 form 元素添加一个 ID 属性,其值为"newnameform"。

  • 创建一个带有"for"属性的标签元素,并将其值设置为"newusername"。

  • 在标签内,添加提示用户输入新用户名的文本。

  • 创建一个输入元素,将"type"属性设置为"text",将"id"属性设置为"newusername",将"name"属性设置为"newusername"。

  • 创建一个按钮元素,将"type"属性设置为"submit",将"form"属性设置为表单的 ID("newnameform"),将"value"属性设置为"Submit"。

  • 在按钮内,添加提示用户提交数据的文本。

示例

<!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>

方法 - 2

以下示例演示如何创建一个按钮来提交多个表单

算法

  • 设置标题。

  • 添加三个不同的表单,每个表单在正文部分中都具有唯一的 ID 属性。

  • 每个表单都应包含一个带有"for"属性的标签和一个带有唯一"id"属性和"name"属性的输入字段。

  • 对于第一个表单,输入字段应具有值为"text"的"type"属性。对于下一个表单,输入字段应具有值为"email"的"type"属性。第三,输入字段应具有值为"tel"的"type"属性。

  • 创建一个按钮元素,其"id"属性为"btn1",文本值为"Submit"。

  • 向按钮元素添加一个"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>

结论

我们可以在网站的联系表单中使用这些类型的按钮。这使得访问者可以轻松地向网站所有者发送消息或请求信息。在电子商务网站中,我们将使用包含用户账单和配送信息字段以及付款方式的表单,并添加一个"提交"按钮来完成购买。许多网站上的登录表单、搜索表单和注册表单通常使用一个按钮来收集多个表单。