JavaScript - Use a div tag to submit data

时间:2018-02-26 17:46:53

标签: javascript jquery html forms post

I saw a website the other day which had a very cool looking checkout system, and it occoured to me that this could not be done using just a regular form.

Basically they were using div tags as radio buttons, but there was no trickery involved of them hiding a radio button.

Example HTML:

<div class="checkout">


<div class="checkout-option" data="option-1">
<img src="example-product-1">
<h3>Example Product 1</h3>
</div>

<div class="checkout-option" data="option-2">
<img src="example-product-2">
<h3>Example Product 2</h3>
</div>

<div class="checkout-option" data="option-3">
<img src="example-product-3">
<h3>Example Product 3</h3>
</div>

<button id="submit-order">Checkout</button>





</div>

So what do I want to happen?:

  1. User presses an option, for example option 2
  2. User presses the checkout button
  3. User is then redirected to whatever page

(And the data of the product they selected is sent to the server )

I have looked everywhere for a solution to this, there is no use of forms and I cannot understand how you would get this to work

Thanks for looking at my question!

1 个答案:

答案 0 :(得分:0)

正如@Taplar所提到的,<form>最适合此目的。

通常,ID对应于数据库中的数据。因此,传递ID足以引用数据。如果您没有以这种方式构建事物,则可以包含其他隐藏的输入以传递必要的数据。

以下是一个例子:

label {
  display: block;
  margin:0 0 1em;
}
h3 {
  display: inline-block;
  margin: 0;
}
.checkout-option input {
  display: none;
}
input:checked~h3 {
  background-color: lightgreen;
}
<form action="//httpbin.org/post" method="post">
  <div class="checkout">

    <label class="checkout-option">
      <input type="radio" name="option" value="1">
      <img src="example-product-1">
      <h3>Example Product 1</h3>
    </label>

    <label class="checkout-option">
      <input type="radio" name="option" value="2">
      <img src="example-product-2">
      <h3>Example Product 2</h3>
    </label>

    <label class="checkout-option">
      <input type="radio" name="option" value="3">
      <img src="example-product-3">
      <h3>Example Product 3</h3>
    </label>

    <button type="submit">Checkout</button>

  </div>
</form>