Skip to content

Instantly share code, notes, and snippets.

@binhtran04
Forked from michelarteta/checkout.js
Created December 23, 2021 09:30
Show Gist options
  • Save binhtran04/77f82fdfc4de652abc40a772ef5e53b9 to your computer and use it in GitHub Desktop.
Save binhtran04/77f82fdfc4de652abc40a772ef5e53b9 to your computer and use it in GitHub Desktop.
Shopify Adds Custom Attributes to Checkout
const citTag = '123456789';
const store = {
order_attributes: [
'citNumberId'
]
}
const storeOrderData = {
attributes: {
citNumberId: citTag
}
};
const { attributes } = storeOrderData;
function injectInputs(element, orderAttributes) {
orderAttributes.forEach((attribute) => {
const $input = document.querySelectorAll(`input[name="checkout[attributes][${attribute}]"]`);
if ($input.length < element.length) {
const $newInput = document.createElement('input');
$newInput.type = 'hidden';
$newInput.name = `checkout[attributes][${attribute}]`;
element.appendChild($newInput);
}
});
}
function setStoreAttributes(data, orderAttributes) {
orderAttributes.forEach((attribute) => {
const $inputs = document.querySelectorAll(`input[name="checkout[attributes][${attribute}]"]`);
$inputs.forEach((input) => {
input.value = data[`${attribute}`];
});
});
}
function updateAttributes() {
const $cartForms = document.querySelectorAll('form[method="post"].edit_checkout');
if ($cartForms.length > 0) {
$cartForms.forEach((form) => {
injectInputs(form, store.order_attributes);
});
}
setStoreAttributes(attributes, store.order_attributes);
}
document.addEventListener('page:change', updateAttributes);
document.addEventListener('page:load', updateAttributes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment