alpine js two way data binding with x-model example

in this Alpine js tutorial we will see x-model example . x-model is use for two way data bind in alpine js . we can bind data form elements like form input. textarea inputs, checkboxes, Radio inputs, Select inputs, any form elements you can bind. x-model set object value to input value.


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>
Alpine js Two Way data binding with x-model Example v2

Alpine js Two Way data binding with x-model Example v2


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>


You can also use few modifier for you requirement


lazy : x-model.lazy="myInput"

number : x-model.number="myInput"

debounce : x-model..debounce="myInput"

throttle : x-model.throttle.500ms="myInput"