1

I am tracking the number of characters typed into a textarea are < 140. I am currently only catching characters on 'keyup' but also want to track if a user copy/paste into the textarea. Any suggestions?

$(function(){
  var limitDiv = $("#limit");
  var limit = limitDiv.data("limit");
  var button = $("input");
  $("textarea").on("keyup", function(){
    var total = this.value.length;
    var diff = limit- total;
    var condition = diff < 0 || total === 0;
    limitDiv.text(diff).toggleClass("red", condition);
    button.prop("disabled", condition);
  }).trigger("keyup");
})
David Thomas
  • 249,100
  • 51
  • 377
  • 410

2 Answers2

1

There is a paste event in jQuery, though its not used very frequently. It seems to still work as of jQuery 2.1.0.

$("#input").on("paste", function(e){
      //code goes here
  }); 

http://jsfiddle.net/gty70qc9/2/

Aweary
  • 2,302
  • 17
  • 26
0

Just add a paste event:

$(function(){
  var limitDiv = $("#limit");
  var limit = limitDiv.data("limit");
  var button = $("input");
  $("textarea").on("keyup paste", function(){
    var total = this.value.length;
    var diff = limit- total;
    var condition = diff < 0 || total === 0;
    limitDiv.text(diff).toggleClass("red", condition);
    button.prop("disabled", condition);
    button.value(total);
  });
})
textarea {
  width: 100%;
  height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<input type="button" value="Submit">
<div id="limit" data-limit="15"></div>
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79