1

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

1 Answer 1

3

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/[email protected]/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/[email protected]/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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.