0

Here I'm using onPaste event :-

$(document).on("paste", ".txtQuestion", function (event e)
    if ( $(".txtQuestion").val().length >= 10) {
        e.preventDefault();
        $(".txtQuestion").addClass("error");
        return false;
    }
    else {
        $(".txtQuestion.error").removeClass("error");
    }
});
Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
  • `paste` will fire before the value is pasted. That is why it is not working. You need to check after the text has been changed. – Sukanya1991 Apr 13 '15 at 13:46

2 Answers2

1

You can have a look at this:

$(document).on("paste keydown", ".txtQuestion", function (e) {
    var $this = $(this); //chache your element
    var max = 10; //set max-value for input
    setTimeout(function () { //workaround for catching the pasted input
        var text = $this.val(); //get the value of the textarea
        if (text.length >= max) { //check for the length
            e.preventDefault();
            $this.addClass("error"); 
            $this.val(text.substring(0, max)); //cut the input to the max
        } else {
            $this.removeClass("error");
        }
    }, 100);

});

Demo

See here for the workaround with the setTimeout for catching the pasted input

Community
  • 1
  • 1
empiric
  • 7,449
  • 6
  • 35
  • 44
0

Wouldn't it be better to just cut whats over the lenght limit? So on change you'll check lenght and substr(0, limit)?

kWeglinski
  • 381
  • 3
  • 14