js校验输入框还可以输入多少个字,区分汉字和非汉字

<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>main.html</title>
<style type="text/css">
</style>
<script type="text/javascript">
    function checkLength (target)
    {
        var maxLength = 100;
        var targetLength = native2ascii (target.value);
        var leftLength = maxLength - targetLength;
        var size = document.getElementById ("size");
        size.innerHTML = size.innerHTML.replace(/(\+|\-)?\d+/, leftLength);
    }
     
    function native2ascii (value)
    {
        var nativecode = value.split ("");
        var len = 0;
        for ( var i = 0; i < nativecode.length; i++)
        {
            var code = Number (nativecode[i].charCodeAt (0));
            if (code > 127)
            {
                len += 2;
            }
            else
            {
                len++;
            }
        }
        return len;
    }
</script>
</head>
<body>
    <textarea onkeyup="checkLength(this)" rows="10" cols="30" style="resize: none;"></textarea>
    <div id="size" style="color: red;">输入100字节数</div>
</body>
</html>

 

posted on 2016-10-14 15:00  laugher_ccc  阅读(497)  评论(0编辑  收藏  举报

导航