Skip to content

Number Input Loading

Save a cart quantity on the server, with a spinner in place of the step buttons until the new total arrives. The change event sends the request, readOnly blocks edits while it runs, and a spinner in the after slot replaces the button parts.

$24.00 $24.00 each

Code

The following example assumes that you have imported the components and set up the theme.

Loading
<div class="number-input-loading">
8 collapsed lines
<div class="cart-item">
<label for="number-input-loading-quantity">Wireless mouse</label>
<output class="line-total">$24.00</output>
<span class="unit-price">$24.00 each</span>
<sv-number-input id="number-input-loading-quantity" max="10" min="1" value="1">
<sv-spinner aria-label="Updating cart" hidden slot="after"></sv-spinner>
</sv-number-input>
</div>
</div>
<script type="application/x-typescript" module>
23 collapsed lines
const unitPrice = 24;
const cartItem = document.querySelector<HTMLElement>(".number-input-loading .cart-item")!;
const numberInput = cartItem.querySelector<NumberInput>("sv-number-input")!;
const updatingSpinner = cartItem.querySelector<HTMLElement>("sv-spinner")!;
const lineTotal = cartItem.querySelector<HTMLOutputElement>(".line-total")!;
const priceFormat = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
numberInput.addEventListener("change", async () => {
setLoading(true);
lineTotal.value = priceFormat.format(await updateCart(numberInput.value ?? 1));
setLoading(false);
});
function setLoading(isLoading: boolean) {
numberInput.readOnly = isLoading;
numberInput.toggleAttribute("data-loading", isLoading);
updatingSpinner.hidden = !isLoading;
}
// Stands in for the request that saves the quantity and returns the new line total
function updateCart(quantity: number) {
return new Promise<number>(resolve => setTimeout(() => resolve(unitPrice * quantity), 1200));
}
</script>
<style>
48 collapsed lines
.number-input-loading {
display: grid;
justify-items: center;
.cart-item {
display: grid;
grid-template-columns: 1fr auto;
gap: 0.25em 1em;
align-items: baseline;
inline-size: min(100%, 18em);
padding: 1em;
background-color: var(--sv-gray-7);
border: 1px solid var(--sv-gray-5);
border-radius: var(--sv-bdr-rad-lg);
}
label,
.line-total {
font-weight: 600;
color: var(--sv-gray-0);
}
.line-total {
font-variant-numeric: tabular-nums;
}
.unit-price {
grid-column: 1 / -1;
font-size: 0.875em;
color: var(--sv-gray-3);
}
sv-number-input {
grid-column: 1 / -1;
margin-block-start: 0.75em;
&[data-loading]::part(decrement-button),
&[data-loading]::part(increment-button) {
display: none;
}
}
sv-spinner {
align-self: center;
margin-inline-end: 0.6em;
font-size: 1.25em;
}
}
</style>