title: Jquery Character Counter for Dynamically Added Text Boxes
body: <p>I am dynamically adding text fields on a button click using Jquery.  I need to add a character counter underneath each text field that gets added, so as the user types they can see how many characters are left.</p>
  
  <p>Right now, what it does is display the div element, but it's treating each text field with the same character countdown, rather than counting the characters in each text field. I have attempted to use .each and .map to loop through the updateCounter div tag, but continue to get the same results. How can I improve this to report the character counter on each textfield?  Thanks-</p>
  
  <p>This Fiddle illustrates the problem: <a href="https://jsfiddle.net/7com4vqz/1/" rel="nofollow">https://jsfiddle.net/7com4vqz/1/</a></p>
  
  <p>HTML:</p>
  
  <pre><code>&lt;input type='button' value='+' id='addUpdate'&gt;
  &lt;input type='button' value='-' id='removeUpdate'&gt;
  
  &lt;div id='TextBoxesGroup'&gt;        
      &lt;div id="TextBoxDiv1"&gt;
          &lt;h4&gt;Update #1&lt;/h4&gt;
          &lt;textarea id="txtUpdates1" name="txtUpdates1" cols="130" rows="5" maxlength="500" class="form-control" placeholder="500 characters max"&gt;&lt;/textarea&gt;
          &lt;div id="updateCounter1"&gt;&lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>JQuery:</p>
  
  <pre><code>//Dynamically added updates.
  var counter = 2;
  $("#addUpdate").click(function ()
  {
      var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
      newTextBoxDiv.after().html('&lt;h4&gt;Update #' + counter + '&lt;/h4&gt;' +
      '&lt;textarea cols="130" rows="5" maxlength="500" class="form-control" placeholder="500 characters max" name="txtUpdates"' + counter + '" id="txtUpdates' + counter + '" value=""&gt;');
      newTextBoxDiv.appendTo("#TextBoxesGroup");
  
      var newCounter = $(document.createElement('div')).attr("id", 'updateCounter' + counter);
      newCounter.after().html('&lt;div name="updateCounter"' + counter + '" id="updateCounter' + counter + '" value=""&gt;');
      newCounter.appendTo("#TextBoxesGroup");
  
      counter++;
  });
  
  $("#removeUpdate").click(function ()
  {
      if (counter == 1)
      {
          alert("No more textboxes to remove");
          return false;
      }
  
      counter--;
  
      $("#TextBoxDiv" + counter).remove();
  });
  
  
  $('body').on('keyup', '[id^=txtUpdates]', function ()
  {
      var max = 500;
      var len = $(this).val().length;
  
      if (len &gt;= max)
      {
          $('[id^=updateCounter]').text(' you have reached the limit');
      }
  
      else
      {
          var char = max - len;
          $('[id^=updateCounter]').text(char + ' characters left');
      }
  });
  </code></pre>