Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

jquery - limit how many characters can be pasted in textarea

Is it possible to detect how many characters are being pasted into a HTML textarea, and cancel the paste if beyond a limit?

Edit: what I am trying to do is prevent the user pasting a massive amount of characters (~3 million) because it crashes some browsers. So I want to cancel the paste before their browser locks up. I am making a document editor where users are likely to try this. But they can type as much as they want.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can do this on jQuery like this:

$(document).ready(function(){
function limits(obj, limit){

    var text = $(obj).val(); 
    var length = text.length;
    if(length > limit){
       $(obj).val(text.substr(0,limit));
     } else { // alert the user of the remaining char. I do alert here, but you can do any other thing you like
      alert(limit -length+ " characters remaining!");
     }
 }


$('textarea').keyup(function(){

    limits($(this), 20);
})

  })

view a demo here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
...