Skip to content
Advertisement

Count characters of dynamically created textareas with different id and name attr

I am having two textareas one under another

<div class="form-group">
<span id="textarea_feedback1"></span>
<span> 🖊Characters left</span>
<br>
<textarea name="answer1" id="answer1" rows="4" placeholder="Type your answer here" areaid="1"></textarea>
<hr>
<span id="textarea_feedback2"></span>
<span> 🖊Characters left</span>
<br>
<textarea name="answer2" id="answer2" rows="4" placeholder="Type your answer here" areaid="2"></textarea>
</div>

Both textareas are created dynamically and they have different id and name attr. At some point, they might be 2, 3, 4… and so on. What I am trying to do is to create a char counter for each textarea that also applies dynamically.

It would have had been easy if the number of the textareas was fixed (i.e, always 2).

But I am having trouble finding a way to apply one and the same JQuery script to textareas with a different name and id attribute.

I was thinking about adding a unique attribute like areaid="" to each textarea, so I can somehow modify dynamically the script.

This is the script I have

$(document).ready(function() {
var text_max = 400;

$('#textarea_feedback1').html('<span>'+text_max + '</span>');

$('#answer1').on('input click keyup', function() {
    var text_length = $('#answer1').val().length;
    var text_remaining = text_max - text_length;

    $('#textarea_feedback1').html('<span>'+text_remaining + '</span>');
});

});

Basically, what I think that it should happen is, that based on the areaid attr to also change the value of the span id="textarea_feedback" and textatea id="answer" to match the areaid value, so somehow the script would work separately to as many textareas I have.

Here is jsfiddle

Advertisement

Answer

Wrap that span and the textarea in an element like div so you can access both easily.

;window.onload = function(){
  var text_max = 400;

  for(var tL=document.querySelectorAll('.dummy textarea'), i=0, j=tL.length; i<j; i++){
    $(tL[i]).on('input click keyup', function(){
        var text_length = this.value.length;
        var text_remaining = text_max - text_length;

        this.parentNode.querySelector('span').textContent = text_remaining
    })
  }
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">

<div class = 'dummy'>
<span id="textarea_feedback1"></span>
<span> 🖊Characters left</span>
<br>
<textarea name="answer1" id="answer1" rows="4" placeholder="Type your answer here" areaid="1"></textarea>
</div>

<hr>

<div class = 'dummy'>
<span id="textarea_feedback2"></span>
<span> 🖊Characters left</span>
<br>
<textarea name="answer2" id="answer2" rows="4" placeholder="Type your answer here" areaid="2"></textarea>
</div>
</div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement