How to Use Bind Data (x-model) in AlpineJS

In this Alpine.js tutorial, we will explore an example of x-model. x-model is used for two-way data binding in Alpine.js. We can bind data to form elements such as input fields, textarea inputs, checkboxes, radio inputs, select inputs, and any other form elements. x-model sets the value of an object to the value of the input.

Example 1

Text in Input element goes to output immediately show result.

<div x-data="{ input : '' }" class="flex justify-center mt-8">
    <input type="text" x-model="input" class="p-2 border-2 rounded shadow">
    <h3 class="mt-2"> Output:</h3>
    <p x-text="input" class="bg-red-100"></p>
</div>

Example 2

Text in Inputs influenced by both inputs.

<div x-data="{ myInput : 'Write Something' }">
    <input type="text" x-model="myInput" class="p-2 border rounded shadow border-1">
    <input type="text" x-model="myInput" class="p-2 border rounded shadow border-1">
</div>
x-model data bind input

Example 3

Select option value.

<div x-data="{ myColor:'' }" class="flex justify-center mt-8">
    <select x-model="myColor" class="p-2">
        <option value="" disabled>Select A Color</option>
        <option>Green</option>
        <option>Red</option>
        <option>Yellow</option>
    </select>
    Select Color: <p x-text="myColor"></p>
</div>

Example 4

alpinejs x-model number.

<div x-data="{ numberValue: 0 }">
    <input type="number" x-bind:value="numberValue" x-on:input="numberValue = $event.target.valueAsNumber">
    <p>Current Value: <span x-text="numberValue"></span></p>
</div>
saim ansari
saim ansari

I'm Saim Ansari, a full-stack developer with 4+ years of hands-on experience who thrives on building web applications that leave a lasting impression. When it comes to tech, I'm particularly adept at Laravel, React, Tailwind CSS, and the Tall Stack