Promo Code Field
Apply a promo code with checking and refusal states; applied codes stay as removable tokens with their saving.
c2-promo-code-field is the promo code field of a checkout, like Shopify’s, Uber Eats’ or Amazon’s: type a code, apply it, see it accepted or refused, and keep each applied code as a removable token with its saving.
Import
import '@c2n/components/promo-code-field'Usage
Checking codes
Set validate to an async function that asks your server. It answers { code, label } for an accepted code (the server’s spelling of the code wins) or { error } for a refused one:
const field = document.querySelector('c2-promo-code-field')!
field.validate = async (code) => {
const result = await api.applyPromo(code)
return result.ok ? { code: result.code, label: result.saving } : { error: result.message }
}
field.addEventListener('apply', ({ detail }) => cart.addDiscount(detail.code))
field.addEventListener('remove', ({ detail }) => cart.removeDiscount(detail.code))While it runs, the field is read-only and the Apply button runs. Without validate, every code is accepted. A code already applied is refused without asking the server, and codes are upper-cased unless case-sensitive.
How many codes
max is how many codes may apply at once (1 by default, 0 for no limit). At the limit the field gives way to the tokens, and removing a token brings it back. codes holds the applied codes, so a cart restored from the server can set it. collapsed starts the field as an “Add a promo code” link, the common checkout pattern.
Accessibility
The field is named “Promo code” (or label), Enter applies, and a refusal shows under the field and describes it. Accepting and removing a code is announced (“SPRING20 applied: −$12.00”), and the tokens are a list named “Applied codes”.