Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript – Character counter for multiple textareas

I have a form on my website with several different textareas.

HTML/PHP

foreach ($bla as $blabla) {
  .... other php-code (not relevant) ....
  echo '<textarea id="textarea['.$blabla["ID"].']" name="textarea" maxlength="1000" onKeyUp="countChars(\'textarea['.$blabla["ID"].']\',\'count\',\'{CHAR}\',1000);""></textarea>';
  echo '<span id="counter">1000</span>';
}

JS:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function countChars(entrance, exit, text, characters) {
  var entranceObj = document.getElementById(entrance);
  var exitObj = document.getElementById(exit);
  var length = characters - idObj.value.length;
  if (length <= 0) {
    length = 0;
    text =
      '<span class="disable" style="color: red;">' +
      text +
      '</span>';
    entranceObj.value = entranceObj.value.substr(0, characters);
  } else if (length <= 20) {
    text =
      '<span style="color: red">' +
      text +
      '</span>';
  }
  exitObj.innerHTML = text.replace("{CHAR}", length);
}

This code works. However, the counter only works for one textarea. Any ideas why it isn’t working on all?

>Solution :

You need to give unique identifiers for each textarea and counter span. Here’s your PHP code modified to match (using heredoc string delimiters to keep it more readable):

foreach ($bla as $key => $blabla) {
    echo <<<BLA
<textarea id="textarea_{$key}" name="textarea_{$key}" maxlength="1000"
 onKeyUp="countChars('{$key}','{CHAR}',1000);""></textarea>
<span id="counter_{$key}">1000</span>
BLA;
}

If the keys in your array aren’t usable as above, then add a counter variable that you increment on each iteration instead, and use that as the key. You’ll notice a difference in the countChars function call, where we just pass the key, or the unique part of textarea_ and counter_ to your Javascript function.

Then, the Javascript function is modified to match:

function countChars(itemId, text, characters) {
    var entranceObj = document.getElementById('textarea_'+itemId);
    var exitObj = document.getElementById('counter_'+itemId);
    // ...
}

We generate the actual IDs for both the textarea and the counter on the basis of the unique bit. Now, you could also pass the full IDs in two arguments, but it’s basically just redundant bulk.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading