alpinejs-character-count

1.0.3Β β€’Β PublicΒ β€’Β Published

Alpine JS Character Count

Track the character count of an input with the option to compare against the max length πŸ”Ÿ

Example

<div x-data="{ message: 'Hello' }">
  <textarea x-model="message" maxlength="50"></textarea>

  <p>You have written <span x-count="message"></span> characters.</p>

  <p>You have <span x-count.50="message"></span> characters remaining.</p>
</div>

This will return the following:

<p>You have written 5 characters.</p> <p>You have 45 characters remaining</p>

The modifier in the example 50 is the max character count which you can pair up with the maxlength attribute on the HTML input. If you want a more dynamic approach to this, you can do the following.

Using Alpine JS Refs

<div x-data="{ message: 'Hello' }">
  <textarea x-model="message" maxlength="100" x-ref="textarea"></textarea>

  <p>You have written <span x-count="message"></span> characters.</p>

  <p>You have <span x-count.textarea="message"></span> characters remaining.</p>
</div>

Instead of passing the max character count as the modifier, you pass the name of an Alpine JS x-ref.

Install

CDN

<script
  defer
  src="https://unpkg.com/alpinejs-character-count@latest/dist/count.min.js"
></script>

<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>

NPM/Yarn

npm i -D alpinejs-character-count

yarn add -D alpinejs-character-count

Then you can register the plugin.

import Alpine from 'alpinejs'
import count from 'alpinejs-character-count'

Alpine.plugin(count)

window.Alpine = Alpine

Alpine.start()

Stats

Package Sidebar

Install

npm i alpinejs-character-count

Weekly Downloads

35

Version

1.0.3

License

MIT

Unpacked Size

5.41 kB

Total Files

9

Last publish

Collaborators

  • markmead