简体   繁体   中英

how to use dynamic variable in update.js shopify

I want yo use test variable in update.js but it shows error when I use as variable but when I pass this value directly it works can someone please tell me how can use dynamic variable to change quantity of existing products in cart

I have updated my code It will allow user to add only 5 items more than 5 items will be removed It will create string which will look like this 32082238341235:0,39470423048307:0,32164693278835:0,32164693835891:1

and finally the all IDs and qunatity will be updated by update.js

I have got error in last step its shows {"status":404,"message":"Cart Error","description":"Cannot find variant"}

when i try to update all products

 jQuery.getJSON('/cart.js', function(cart) { var items_new = cart.items; var count = 0; count = cart.item_count; var item_to_remove = count - 5; if (count > 5) { var item_to_remove = count - 5; var combine = "" if (item_to_remove > 0) { for (var i = 0; i < items_new.length; i++) { if (count > 5) { var c_id = items_new[i].variant_id; var c_quantity = items_new[i].quantity; if (c_quantity >= item_to_remove) { var q = c_quantity - item_to_remove var data_multiple = c_id + ":" + q + ","; debugger; count = count - item_to_remove; console.log(data_multiple); var combine = combine + data_multiple; } else { var data_single = c_id + ":" + 0 + ","; count = count - c_quantity; item_to_remove = item_to_remove - c_quantity console.log(data_single) var combine = combine + data_single; } } } console.log(combine.slice(0, -1)); var test = combine.slice(0, -1); console.log({ updates: { test } }); jQuery.post('/cart/update.js', { updates: { test } }); } t._rerenderCart() } t.sidebarDrawer.open() });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You need to store test as an object within parentheses {} and then pass to updates by using the spread ... operator.

 var test = {39470423048307: 0, 32164693278835: 0, 32164693835891: 1}; console.log({updates: {...test}}); jQuery.post('/cart/update.js', {updates:{...test}});
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM