Last active
August 16, 2023 15:47
-
-
Save michelarteta/c909b395e260b582fcd700936b52a67a to your computer and use it in GitHub Desktop.
Shopify Adds Custom Attributes to Checkout
This file contains 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
Does it work only for Shopify Plus stores? I'm trying to do this in a non-plus store but doesn't work.