I am having trouble updating my cart through JS body input. I want to update the cart based on a customer input into a text field. The customEngraving variable is pricing for a product I have already created on Ecwid and each index translates to a price point. I am new to the Ecwid API so any help would be greatly appreciated.
Ecwid.OnAPILoaded.add(function(page) {
var customEngraving = [0,0,0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17]
var customInput = document.querySelector(‘CSSSelector’);
if (customInput) {
customInput.addEventListener('input', async function() {
try {
var engravingProduct=await getEngravingProduct();
const items = Ecwid.Cart.get().items;
// if there is an engraving in the cart, remove it
for (let i=0; i<items.length; i++) {
if (items[i]['id']=='207127971') {
Ecwid.Cart.removeProduct(i);
break;
}
}
// add engraving to cart
const ind=customEngraving[customInput.length];
var charCount=engravingProduct['options'][2]['choices'][ind];
engravingProduct['options'][2]['choices']=charCount;
Ecwid.Cart.addProduct(engravingProduct);
} catch (error) {console.error('Error processing input:', error);}
});
}
});
async function getEngravingProduct() {
const options = {
method: ‘GET’,
headers: {accept: ‘application/json’, Authorization: ‘MyToken’}
};
try {
const response = await fetch('url', options)
const obj = await response.json();
return obj;
} catch (error) {
console.log(error);
throw error;
}
}
I have made sure that the getEngravingProduct() function works as well as the section where the correct product is being added to the cart. I think I might be getting tripped up by the Ecwid syntax, but any and all help is appreciated.
Cabot McTavish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.