Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
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:

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda