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

I'm a little lost. I need to add a class to the label if the text input has a value, either on pag

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
Add a ment  | 

1 Answer 1

Reset to default 6

we 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信