简体   繁体   中英

Submit form to different URLs based on checkbox selected

example

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

if the 1st checkbox checked it will submit to this action="url"

if the 2st checkbox checked it will submit to this action="url"

if the 3st checkbox checked it will submit to this action="url"

how can I achieve this.

Thanks in advance

One way of going about this is by adding a data attribute to the checkbox fields.

Each checkbox can have a data attribute (in this instance we can call it data-url ) and you can assign a URL to it.

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

Note:

  • HTML data attributes have to start with data-

You can then simply grab the URL for the selected checkbox in Javascript like this:

const URL = element.dataset.url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM