【发布时间】:2017-06-03 04:10:50
【问题描述】:
在提供多种产品的产品页面上工作。复选框用于选择最多 3 种产品,然后将它们添加到购物车 - 从商店库存中提取产品。
一切正常 - 除了解决添加到购物车后,我无法弄清楚 jQuery 将复选框直接连接到产品的数量 1。
这是我在 Shopify 上的 Liquid 中的代码 sn-p:
<script type="text/javascript" charset="utf-8">
//<![CDATA[
// Including jQuery conditionally
if (typeof jQuery === 'undefined') {
document.write({{ "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" | script_tag | json }});
document.write('<script type="text/javascript">jQuery.noConflict();<\/script>');
}
//]]>
</script>
<script>
$('input[type=checkbox]').change(function(e){
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false)
alert("Sorry you may only select up to three!");
}
});
{% assign linklist = linklists['order-form'] %}
var length = {{ linklist.links.size }};
$(document).ready(function () {
$("#quantity-0").focus();
$("#submit-table").click(function(e) {
e.preventDefault();
//array for Variant Titles
var toAdd = new Array();
var qty ;
for(i=0; i < length; i++){
toAdd.push({
variant_id: $("#variant-"+i).val(),
quantity_id: $("#quantity-"+i).val() || 0
});
}
function moveAlong(){
if (toAdd.length) {
var request = toAdd.shift();
var tempId= request.variant_id;
var tempQty = request.quantity_id;
var params = {
type: 'POST',
url: '/cart/add.js',
data: 'quantity='+tempQty+'&id='+tempId,
dataType: 'json',
success: function(line_item) {
//console.log("success!");
moveAlong();
},
error: function() {
//console.log("fail");
moveAlong();
}
};
$.ajax(params);
}
else {
document.location.href = '/cart';
}
};
moveAlong();
});
});
</script>
这里是实际列表的产品页面脚本:
{% assign linklist = linklists['order-form'] %}
<form>
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr id="cart-headlines">
<td class="cart-thumb"> </td>
<td class="cart-title">Product Title</td>
<td class="cart-unitprice">Price</td>
<td class="cart-quantity">Select</td>
</tr>
{% for link in linklist.links %}
<tr>
<td >
<a href="" title="View Page">
<img src="{{ link.object.featured_image | product_img_url: 'thumb' }}" alt="{{ link.object.title | escape }}" />
</a>
</td>
<td >
<a href="{{ link.object.url}}" title="View {{item.title | escape }} Page">
{{ link.object.title | truncatewords:5 }}
</a>
</td>
<td>
{{ link.object.variants.first.price | money }}
</td>
<td>
<input type="hidden" value="{{ link.object.variants.first.id }}" id="variant-{{ forloop.index0 }}"/>
<input type="checkbox" id="quantity_id" class="single-checkbox"
/> </td>
</tr>
{% endfor %}
</tbody>
</table>
<p style='text-align:right;'>
<input type="submit" value="Add to cart" id="submit-table"/>
</p>
</form>
好像很接近了。目前 - 单击任何复选框会将所有产品添加到购物车。
我想点击一个复选框并将其转换为该特定产品的 1 个数量。
非常感谢您的帮助。
最好的
【问题讨论】:
-
脚本在这里寻找一个值 quantity_id: $("#quantity-"+i).val() 但您的代码没有 #quantity_1 (例如)它只有 # quantity_id,也没有为 #quantity_X 设置值,所以当你得到排序的复选框的 id 时,你必须将 value="1" 添加到它
标签: jquery html checkbox shopify liquid