Home > Mobile >  JavaScript - Character counter for multiple textareas
JavaScript - Character counter for multiple textareas

Time:05-08

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:

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  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?

CodePudding user response:

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. It's cleaner to keep function signatures minimal and regenerate patterns like this.

  • Related