需要从表单中获取Selected Option值并通过jquery / javascript传回

时间:2016-07-26 17:53:28

标签: javascript jquery html forms

我需要动态获取用户选择的任何选项的值,并在按钮点击时将该值传递回Facebook Pixel。

请参阅脚本区域中的 SELECTED OPTION VALUE

      <form action="/cart/add" method="post" enctype="multipart/form-data" class="AddToBagForm text-center medium-up--text-left" novalidate>    
        <select name="id" id="product-select-2585865157" class="product-single__variants">
              <option  selected="selected"  value="7534116741">White Marble / S - $39.95 USD</option>
              <option  value="7534116869">White Marble / L - $39.95 USD</option>
              <option  value="7534117061">Midnight / S - $39.95 USD</option>
              <option  value="7534117253">Midnight / L - $39.95 USD</option>
              <option  value="9032311493">Maroon / M - $39.95 USD</option>
              <option  value="9032318853">Maroon / L - $39.95 USD</option>
        </select>   
        <div class="add-container clearfix">   
          <a href="#" class="btn--primary BIS_trigger" data-product-handle="mighty-ganesh-flowy-top" data-variant-id="7534116741">Get Notified</a>
          <div class="quantity-field">
            <label for="Quantity" class="quantity-selector">Qty:</label>
            <input type="number" id="Quantity" name="quantity" value="1" min="1" max="3" class="quantity-selector">
          </div>
          <button type="submit" name="add" class="AddToBag btn--primary" id="add-to-cart" >
            <span class="AddToBagText">Add to Bag</span>
          </button>  
        </div>

        <script type="text/javascript">
          $('#add-to-cart').click(function() {
            fbq('track', 'AddToCart', {
              content_ids: '{{ product.id }}.' + **SELECTED OPTION VALUE**,
              content_type: 'product',
              value: {{ product.price | money_without_currency}},
            });
          });
        </script>

      </form>

1 个答案:

答案 0 :(得分:1)

由于您已经使用了该库,因此您可以获得select元素的所选选项值through the .val() function with jQuery

$('#product-select-2585865157').val()

或者,因为似乎生成了id$('select.product-single__variants').val()

您的最终JavaScript应如下所示:

 $('#add-to-cart').click(function() {
      var selection = $('#product-select-2585865157').val();
      /* var selection = $('select.product-single__variants').val(); */

      fbq('track', 'AddToCart', {
          content_ids: '{{ product.id }}.' + selection,
          content_type: 'product',
          value: {{ product.price | money_without_currency}},
      });
 });