Brian
Brian

Reputation: 147

JQuery text area character count

I am trying to use Jquery to count the characters in a text area, here is what i have so far..

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

 <script  type="text/javascript">
     $(document).ready(function() {
            $("#textfield").on('keyup, paste', function(){

            var Characters = ("#textfield").val().replace(/(<([^>]+)>)/ig,"").length;

            $("#counter").text("Characters left: " + (1500 - Characters));

        });
    });
</script>

</head>
<body>

 <form  id="input_form"  method="POST" action="?">
 <textarea  id="textfield"></textarea>
</form>

<div id="counter"></div>  

</body>
</html>

Nothing is being output into my div... Any ideas why?

Upvotes: 3

Views: 3720

Answers (4)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

Here is an example of a jQuery plugin that can take care of most of the logic for you. The best thing about this is that it's reusable.

The documented options and appropriately named variables and function should be enough to follow the logic. Just keep in mind that the data-length attribute overrides the configurable option for the plugin.

$(document).ready(function() {
  $('textarea').textLimit({
    textPrefix: "Remaining characters:",
    onUpdate: function() { this.removeClass('warn error'); },
    onLimitExceeded: function() { this.addClass('error'); },
    onLimitApproaching: function() { this.addClass('warn'); }
  });
});

(function($) {
  var defaultOptions = {
    limit: 100, // The default character limit
    textPrefix: "Characters left:", // Default prefix for the character count message
    thresholdPercentage: 80, // Percentage of limit at which to notify approaching limit
    onUpdate: function() {}, // Callback when the textarea is updated
    onLimitExceeded: function() {}, // Callback when the character limit is exceeded
    onLimitApproaching: function() {} // Callback when approaching the character limit
  };

  $.fn.textLimit = function(options) {
    var opts = $.extend({}, defaultOptions, options);

    return this.each(function() {
      var $this = $(this);
      var limit = parseInt($this.data('limit'), 10) || opts.limit;

      function updateDescription() {
        return opts.textPrefix + " " + (limit - $this.val().length);
      }

      function handleUpdate(e) {
        var charCount = $this.val().length;
        var description = updateDescription();
        var $wrapper = $this.closest('.text-limit-wrapper');
        $wrapper.find('.text-limit-desc').text(description);

        opts.onUpdate.call($wrapper);

        if (charCount >= limit) {
          opts.onLimitExceeded.call($wrapper);
        } else if (charCount >= limit * (opts.thresholdPercentage / 100)) {
          opts.onLimitApproaching.call($wrapper);
        }
      }

      $this.attr('maxlength', limit)
           .wrap($('<div>').addClass('text-limit-wrapper'))
           .parent().append($('<span>')
             .addClass('text-limit-desc')
             .attr('aria-live', 'polite')
             .text(updateDescription()));

      $this.on('keyup paste', handleUpdate);
    });
  };
})(jQuery);
.text-limit-wrapper .text-limit-desc {
  display: block;
}

.text-limit-wrapper.warn .text-limit-desc {
  color: DarkOrange;
}

.text-limit-wrapper.error .text-limit-desc {
  color: Red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<form name="input_form" method="POST" action="?">
  <textarea name="details" cols="60" rows="5"
    placeholder="Details" data-limit="150">Hello World!</textarea>
  <br>
  <textarea name="other" cols="60" rows="3"
    placeholder="Other" data-limit="80"></textarea>
</form>

Upvotes: 0

user18435906
user18435906

Reputation: 27

In addition to above jquery code need to add maxlenth in following code to 1500 so that it limit the characters upto 1500.

<textarea  id="textfield" maxlength="1500"></textarea>

Upvotes: -1

Milind Anantwar
Milind Anantwar

Reputation: 82231

You have two issues in your code

1) you do not need comma while passing the event list/multiple events to on method. it should be .on('keyup paste'

2) You are missing jquery selector while getting text value of textarea. you should use

 $("#textfield").on('keyup, paste', function(){
        var Characters = $("#textfield").val().replace(/(<([^>]+)>)/ig,"").length;
        $("#counter").text("Characters left: " + (1500 - Characters));
 });

Working Demo

Upvotes: 2

Jai
Jai

Reputation: 74738

Two issues are there:

  1. .on('keyup paste' remove comma from here
  2. $("#textfield").val().replace here $ is missing from the selector.

     $(document).ready(function() {
            $("#textfield").on('keyup paste', function(){ // <---remove ',' comma

            var Characters = $("#textfield").val().replace(/(<([^>]+)>)/ig,"").length; // '$' is missing from the selector

            $("#counter").text("Characters left: " + (1500 - Characters));

        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 <form  id="input_form"  method="POST" action="?">
 <textarea  id="textfield"></textarea>
</form>

<div id="counter"></div>

Upvotes: 1

Related Questions