0

I like to match textarea data with span data when you type in each textarea to retun char left in the span with same data

How to match them ?

html

 <span data-lang="gb"></span>
<textarea data-lang="gb"></textarea>

<span data-lang="en"></span>
<textarea data-lang="en"></textarea>

jquery

 $('textarea').each(function(){
  var lang = $(this).data('lang');
  $(this).keyup(function(){
    if (this.value.length > 50) {
      return false;
    }
    $('span').html("(characters left: " +(50 - $(this).val().length) + " )");
  });
});

2 Answers2

0

You can make a data attribute in your text area telling it what is it's counter element and use it to select and update the counter.

Like this:

$("[data-counter]").on('input', function (e) {
  var counter = $(this).data('counter');
  var $counter = $(counter);
  var maxlength = parseInt($(this).attr('maxlength'));
  var count = $(this).val().length;
  $counter.text('Characters left: ' + (maxlength - count));
}).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea id="mytext" data-counter="#mytextcounter" maxlength="50"></textarea>
<span id="mytextcounter"></span>
Phiter
  • 14,570
  • 14
  • 50
  • 84
0

You are very close to the point:

$('textarea').each(function(){
  var lang = $(this).data('lang');
  $(this).keyup(function(){
    if (this.value.length > 50) {
      return false;
    }
    $('span[data-lang="'+lang+'"]').html("(characters left: " +(50 - $(this).val().length) + " )");
  });
});

As you can see for example here you can select an element by data attribute. Please note that this code is untested

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74