【问题标题】:Submit form to different URLs based on checkbox selected根据选中的复选框将表单提交到不同的 URL
【发布时间】:2020-11-04 20:36:41
【问题描述】:

示例

   <form method="post" class="customform" id="customform" data-async="true" data-recaptcha="false">
      <p>
        <input type="text" placeholder="First Name" name="first_name" required />
      </p>
      <p>
        <input type="text" placeholder="Last Name" name="last_name" required />
      </p>
      <p>
        <input type="email" placeholder="Email" name="email" required />
      </p>
      <p>
        <input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
        <label for="vehicle1"> I have a bike</label>
      </p>
      <p>
        <input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
        <label for="vehicle2"> I have a car</label>
      </p>
      <p>
        <input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
        <label for="vehicle3"> I have a boat</label>
      </p>            
      <p><button type="submit">Submit</button></p>
    </form>

如果第一个复选框被选中,它将提交给这个 action="url"

如果第二个复选框被选中,它将提交给这个 action="url"

如果选中了第三个复选框,它将提交给这个 action="url"

我怎样才能做到这一点。

提前致谢

【问题讨论】:

标签: javascript html forms


【解决方案1】:

解决此问题的一种方法是向复选框字段添加数据属性。

每个复选框都可以有一个数据属性(在这种情况下,我们可以称之为data-url),您可以为其分配一个 URL。

<p>
  <input data-url="someURL" type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
  <label for="vehicle1"> I have a bike</label>
</p>

注意:

  • HTML 数据属性必须以data- 开头

然后,您可以像这样在 Javascript 中简单地获取所选复选框的 URL:

const URL = element.dataset.url

【讨论】:

  • 我会比 kyou 试试这个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-23
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 2012-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多