Search code examples
htmljquerycountmaxcharacter

Multiple count of numbers of characters to span?


I have been unsuccessful in trying to add two seperate maximum character fields to a form. I have tried renaming the element ids and changing the var i and c but to no avail. Thanks

Fiddle http://jsfiddle.net/rLkcy0t4/

Here is the code.

var maxchar = 160;
var i = document.getElementById("textinput");
var c = document.getElementById("count");
c.innerHTML = maxchar;

i.addEventListener("keydown", count);

function count(e) {
  var len = i.value.length;
  if (len >= maxchar) {
    e.preventDefault();
  } else {
    c.innerHTML = maxchar - len - 1;
  }
}
textarea {
  display: block;
  width: 200 px;
  height: 100 px;
}
Remaining characters: <span id="count"></span>
<textarea id="textinput">
    </textarea>


Solution

  • Delegation and data attributes will help

    window.addEventListener("load", function() {
      const container = document.getElementById("container")
      container.querySelectorAll("textarea").forEach(ta => ta.dataset.max = ta.dataset.cnt); // save 
      container.addEventListener("input", function(e) {
        const tgt = e.target;
        if (tgt.matches("textarea")) {
          const maxchar = +tgt.dataset.max;
          let cnt = +tgt.dataset.cnt;
          const c = tgt.previousElementSibling;
          cnt = maxchar - tgt.value.length;
          if (cnt < 0) {
            tgt.value = tgt.value.slice(0, maxchar);
            cnt = 0;
          }
          tgt.dataset.cnt = cnt;
          c.textContent = cnt;
        }
      })
    })
    textarea {
      display: block;
      width: 200 px;
      height: 100 px;
    }
    <div id="container">
      Remaining characters: <span class="count"></span><textarea id="textinput1" data-cnt="160"></textarea>
      <hr/> Remaining characters: <span class="count"></span><textarea id="textinput2" data-cnt="100"></textarea>
    </div>