javascriptalpine.js

Automatically trim text using Alpine.js


How can I use Alpine.js to automatically trim text in an input or textarea?


Solution

  • This can be done with the x-on directive.

    One can use x-on:change to trim leading/trailing spaces after the control loses focus:

    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.14.8/dist/cdn.min.js"></script>
    
    <form x-data="{ value: '' }">
      <input type='text' 
             x-model="value"
             x-on:change="value = value.trim()" />
    </form>

    Alternatively, one could use x-on:keyup, for immediate trimming:

    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.14.8/dist/cdn.min.js"></script>
    
    <form x-data="{ value: '' }">
      <input type='text' 
             x-model="value"
             x-on:keyup="value = value.trim()" />
    </form>

    But as one can see in the second demo, it isn't as friendly as the first one, and it's hard to add spaces between words.