x-model Directive

Two‑way binding for form inputs – keep UI and data in sync effortlessly.

What is x-model?

x-model creates a two‑way binding between form inputs and Alpine data. When the input changes, the data updates, and vice‑versa. This works for text inputs, textareas, checkboxes, radio buttons, and select dropdowns.

When to Use

Use x-model for any form field that needs to be in sync with your component's state. It’s the cornerstone of interactive forms in Alpine.

Text Input Example

Code
<div x-data="{ name: '' }">
  <input x-model="name" placeholder="Your name">
  <p>Hello, <span x-text="name"></span></p>
</div>

Modifiers

  • .number – converts the value to a number.
  • .trim – trims whitespace.
  • .lazy – updates data on change instead of input (useful for performance).
  • .debounce.300 – debounces the update by 300ms (good for live search).

Checkboxes & Radio Buttons

Code
<!-- Single checkbox (boolean) -->
<input type="checkbox" x-model="agree">

<!-- Multiple checkboxes (array) -->
<input type="checkbox" value="apple" x-model="fruits">
<input type="checkbox" value="banana" x-model="fruits">

<!-- Radio buttons -->
<input type="radio" value="light" x-model="theme">
<input type="radio" value="dark" x-model="theme">

Select Dropdown

Code
<select x-model="selectedCountry">
  <option value="">Choose</option>
  <option value="US">United States</option>
  <option value="IN">India</option>
</select>
Does x-model work with custom components?

Yes, but you'll need to implement the appropriate interface. For simple cases, you can use events or Alpine.bind() to create a reusable custom input.

💡 Tip

Always add a name attribute if you’re doing traditional form submissions – it helps with autofill and accessibility.

Helpful? Share this page!↑ Back to top