Specify Max Length For Text Fields - jQuery maxLength.js

Specify Max Length For Text Fields - jQuery maxLength.js

Yet another jQuery max length plugin which limits the number of characters allowed to be typed in a text field with a basic character counter. Supports textarea, input field and any inline elements.

1. Wrap your text fields into DIV containers and specify the maximum number of characters using the native maxlength attribute or data-val-length attribute.

<div class="form-group">
  <input
      type="number"
      maxlength="10"
      class="form-control"
  >
</div>
<div class="form-group">
  <span
      data-val-length="parent"
  >
  </span>
  <input
      type="text"
      maxlength="20"
      class="form-control"
  >
</div>
<div class="form-group">
  <textarea maxlength="50" name="" id="" cols="30" rows="10" class="form-control"></textarea>
</div>

2. Insert the jQuery maxLength.js script after jQuery.

<script src="https://unpkg.com/[email protected]/dist/jquery.js"></script>
<script src="jQuery.maxlength.js"></script>

3. Call the function on the wrapper element and the plugin will take care of the rest.

$('div.form-group').maxlength();

4. The generated HTML for the character counter.

<span data-val-length="parent">
  <span class="text-limit">
    <span data-val-length="target">8</span>
    <span data-val-length="max">/20</span>
   </span>
</span>

5. Default plugin options.

$('div.form-group').maxlength({
  valName: '[maxlength]',
  target: '[data-val-length=target]',
  maxTarget: '[data-val-length=max]',
  parent: '[data-val-length=parent]'
});

This awesome jQuery plugin is developed by tg0825. For more Advanced Usages, please check the demo page or visit the official website.

  • Publication date: 13.02.2018
  • Source