Created
May 24, 2019 18:57
-
-
Save git-willie/fc1635f0ba41e36fbc3616bfc4fbc893 to your computer and use it in GitHub Desktop.
Bundle products and add all to cart after customization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(document).on('click', '#finish-customization', function(e){ | |
e.preventDefault(); | |
bundle_prefix = "{{ product.handle | replace: '-','_' }}"; | |
bundle_id = Math.floor((Math.random() * 100000) + 1); | |
$('input[name="properties[Custom Product ID]"]').val(bundle_prefix+'_'+bundle_id); | |
$(this).find('span').html('Adding to Cart'); | |
var $result = decodeURIComponent($('#AddToCartForm-{{ section.id }}').serialize()); | |
$result = $result.split('&'); | |
var option1 = ""; | |
var variants = []; | |
var properties = []; | |
var current_id = ''; | |
var current_properties = ''; | |
for(var i = 0; i < $result.length; i++){ | |
var obj = $result[i]; | |
if(obj.indexOf('id[]=') != -1){ | |
if ( current_id != obj) { | |
variants.push({ | |
quantity: 1, | |
id: obj.substring(5), | |
properties: [] | |
}) | |
} | |
current_id = obj; | |
} | |
else if(obj.indexOf('properties[') != -1){ | |
if ( current_properties != obj) { | |
var id_array = obj.match(/[^[\]]+(?=])/g); | |
id = id_array[0]; | |
var plus = '+'; | |
if (id.indexOf(plus) !== -1) { | |
id = id.replace(/\+/g,' '); | |
} | |
var value = obj.substring(obj.indexOf('=') + 1); | |
if (value.indexOf(plus) !== -1) { | |
value = value.replace(/\+/g,' '); | |
} | |
var property = {}; | |
property['key'] = id; | |
property['value'] = value; | |
properties.push(property); | |
} | |
current_properties = obj; | |
} | |
else if(obj.indexOf('quantity=') != -1){ | |
// | |
} | |
else if(obj.indexOf('option1') != -1){ | |
option1 = obj.substring(obj.indexOf('=') + 1); | |
} | |
} | |
// console.log(option1, variants, properties); | |
// return false; | |
for(var i = 0; i < variants.length; i++){ | |
var variant = variants[i]; | |
var props = []; | |
if(i == 0){ | |
variant['option1'] = option1; | |
props = properties; | |
} | |
else{ | |
props.push(properties[0]); | |
} | |
variant['properties'] = {}; | |
for(var c = 0; c < props.length; c++){ | |
var obj = props[c]; | |
variant['properties'][obj.key] = obj.value; | |
} | |
var ajaxCall = $.ajax({ | |
type: 'POST', | |
url: '/cart/add.js', | |
data: variant, | |
// success: success, | |
// dataType: json, | |
async:false | |
}); | |
// console.log(ajaxCall); | |
} | |
window.location.href = "/cart"; | |
// console.log(option1, variants, properties); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment