JavaScript-使用DIV标签提交数据



我前几天看到了一个非常酷的结帐系统的网站,这对我而言,这不能仅使用常规表格完成。

基本上,他们将DIV标签用作收音机按钮,但是他们隐藏了一个无线电按钮。

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

那我想发生什么?:

  1. 用户按选项,例如选项2
  2. 用户按Checkout按钮
  3. 然后将用户重定向到任何页面

(并且他们选择的产品的数据发送到服务器(

我到处都在寻找解决方案,没有形式的用途,我不明白您将如何使其工作

感谢您查看我的问题!

这将使您开始使用"无线电键"样式的DIV。

有人单击提交(结帐(按钮时,您可以抓住"活动"div的值并在JavaScript变量中创建表单。然后,使用.append()将形式注入网页正文,然后使用.submit()提交刚刚创建的/刚刚注射的表单。

$('.checkout-option').click(function(){
   $('.checkout-option').removeClass('active');
   $(this).addClass('active');
});
$('#submit-order').click(function(){
  var prod = $('.checkout-option.active h3').text();
  alert(prod);
  var myfrm = '<form id="theMyForm" action="somefile.html" method="post">
     <input name="opt-selected" value="' +prod+ '" />
     <input name="notice" value="You need to use backslash when breaking strings" />
     </form>';
  $('body').append(myfrm);
  $('#theMyForm').submit();
});
.checkout-option{display:inline-block;width:100px;margin-right:10px;background:darkcyan;color:white;padding:10px;font-size:.9rem;border:1px solid transparent;}
.active{background:white;color:darkcyan;border:1px solid darkcyan;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>

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

通常,IDS对应于数据库中的数据。因此,传递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>

最新更新