Loading

jquery 限制文本域输入大小限制

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>文本域输入字数限制</title>
</head>
<body>
    <div class="container">
  <textarea name="content" id="content" cols="100" rows="10"></textarea>
  <span>0/10</span>
 </div>
</body>
</html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<script type="text/javascript" charset="utf-8">
   
$(function(){
    //第一种:
    $(document).on('input propertychange',"#content",function(){
         var self = $(this);
         var content = self.val();
         
         if (content.length > 10){
                
             self.val(content.substring(0,10));
         } 
         
         self.siblings('span').text(self.val().length+'/'+10);
    });
    
    //第二种:
    $('#content').bind('input propertychange',function() {
         var self = $(this);
     
         var content = self.val();
         
         if (content.length > 10){
                
             self.val(content.substring(0,10));
         } 
         
         self.siblings('span').text(self.val().length+'/'+10);
    })
     
    
})
    
</script>

 

posted @ 2022-08-28 17:19  Carvers  阅读(27)  评论(0)    收藏  举报