如何在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.