Home > Back-end >  Multiple count of numbers of characters to span?
Multiple count of numbers of characters to span?

Time:03-16

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>

CodePudding user response:

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 ></span><textarea id="textinput1" data-cnt="160"></textarea>
  <hr/> Remaining characters: <span ></span><textarea id="textinput2" data-cnt="100"></textarea>
</div>

CodePudding user response:

The problem in your fiddle is you are declaring multiple variable with the same name. You declare i and c twice. You also declare the function count twice. Rename half of those variables to something unique and it should work how you expect it to.

You can see a working example in this fiddle.

  • Related