-
-
Save binhtran04/77f82fdfc4de652abc40a772ef5e53b9 to your computer and use it in GitHub Desktop.
Shopify Adds Custom Attributes to Checkout
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
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