Neatpixels
Neatpixels

Reputation: 97

Update Alpinejs x-data when input has a value on page load or user change

I'm a little lost. I need to add a class to the label if the text input has a value, either on page load (if input is prefilled) or when user enters a vale. And I need to remove those classes if the user removes the text from the input.

.has-value {color:red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/2.3.0/alpine.js"></script>

<form x-data='{value:false}'>
  <label for='example' :class='{"has-value": value }'>Label </label>
  <input id='example' name='example' type='text' x-on:change='value = true' />
</form>

Upvotes: 1

Views: 7577

Answers (1)

Irfan
Irfan

Reputation: 1030

we can use x-model attribute from alpinejs to bind the input text to alpine component property. Now we can check if the input has a value by checking its length.


<form x-data='{value: ""}'>
    <label for='example' :class='{"has-value": value.length > 0 }'>Label </label>
    <input id='example' name='example' type='text' x-model="value" />
</form>

If you want to set an initial value for the input, you can do it in the alpinejs component as shown below


<form x-data='{value: "initial-value"}'>
    <label for='example' :class='{"has-value": value.length > 0 }'>Label </label>
    <input id='example' name='example' type='text' x-model="value" />
</form>

Note that I have used value.length > 0 since has-value class should be added if there is some input in the field.

Upvotes: 6

Related Questions