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=".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>
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./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>
Share
Improve this question
asked Feb 14, 2021 at 23:43
NeatpixelsNeatpixels
972 silver badges10 bronze badges
1 Answer
Reset to default 6we can use x-model
attribute from alpinejs
to bind the input text to alpine ponent 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 ponent 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744252547a4565237.html
评论列表(0条)