Home > Web Front-end > JS Tutorial > body text

Detailed example of jquery implementation to limit the number of input words in textarea

小云云
Release: 2017-12-29 10:41:43
Original
1084 people have browsed it

How does jquery limit the number of words entered in textarea? This article mainly introduces in detail the method of using jquery to limit the number of words entered in a textarea. It has certain reference value. Interested friends can refer to it. I hope it can help you.

Friends in need can refer to the examples I wrote. Of course, if there are any mistakes, I hope everyone can point them out in time so that we can learn and make progress together.


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>textarea 限制字数</title>
 <style>
  .container{
   position: relative;
   width: 730px;
  }
  .container span{
   position: absolute;
   bottom: 20px;
   right: 30px;
  }
 </style>
</head>
<body>
 <p class="container">
  <textarea name="content" id="content" cols="100" rows="10"></textarea>
  <span>0/10</span>
 </p>
 <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
 <script>
  $(function(){
    /**
    * textarea 限制输入字数
    * @param string str 类名或ID
    * @param number num 限制输入的字数
    */
   function limitImport(str,num){
    $(document).on(&#39;input propertychange&#39;,str,function(){
     var self = $(this);
     var content = self.val();
     if (content.length > num){
      self.val(content.substring(0,num));
     } 
     self.siblings(&#39;span&#39;).text(self.val().length+&#39;/&#39;+num);
    });
   }

   //用法示例
   limitImport(&#39;#content&#39;,10);

  })
 </script>
</body>
</html>
Copy after login

Related recommendations: How to use

#html's