最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论