JQuery calculate textarea Chinese word of the remaining number of small procedures

  • 2020-03-30 00:02:30
  • OfStack


<div class="area">
        <p>
             You can also type in <b class="num">140</b> word </p>
        <textarea class="chackTextarea"></textarea>
    </div>

 
<script type="text/javascript">
    var txtobj = {
        divName: "area", //Class of the outer container
        textareaName: "chackTextarea", //The textarea class
        numName: "num", //Number of class
        num: 140 //The maximum number of Numbers
    }
    var textareaFn = function () {
        //Define variables
        var $onthis; //Points to the current
        var $divname = txtobj.divName; //Class of the outer container
        var $textareaName = txtobj.textareaName; //The textarea class
        var $numName = txtobj.numName; //Number of class
        var $num = txtobj.num; //The maximum number of Numbers
        function isChinese(str) {  //Whether it's Chinese or not
            var reCh = /[u00-uff]/;
            return !reCh.test(str);
        }
        function numChange() {
            var strlen = 0; //The initial definition length is 0
            var txtval = $.trim($onthis.val());
            for (var i = 0; i < txtval.length; i++) {
                if (isChinese(txtval.charAt(i)) == true) {
                    strlen = strlen + 2; //Chinese for 2 characters
                } else {
                    strlen = strlen + 1; //One character in English
                }
            }
            strlen = Math.ceil(strlen / 2); //Divide the sum of Chinese and English by 2 to make an integer
            if ($num - strlen < 0) {
                $par.html(" beyond  <b style='color:red;font-weight:lighter' class=" + $numName + ">" + Math.abs($num - strlen) + "</b>  word "); //Out of style
            }
            else {
                $par.html(" You can also type in  <b class=" + $numName + ">" + ($num - strlen) + "</b>  word "); //The normal time
            }
            $b.html($num - strlen);
        }
        $("." + $textareaName).live("focus", function () {
            $b = $(this).parents("." + $divname).find("." + $numName); //Gets the current number
            $par = $b.parent();
            $onthis = $(this); //Gets the current textarea
            var setNum = setInterval(numChange, 500);
        });
    }
    textareaFn();
</script>


Related articles: