jQuery实现还能输入N字符

页面:

<table cellpadding="0" cellspacing="0" border="0" width="100%">
                        <tr>
                            <td>
                                <textarea name="" id="doc" cols="30" rows="10"></textarea>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <div class="face">
                                    <img src="/sitecn/images/face.jpg" /></div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                还能输入<span id="count"></span>字
                                <input type="button" class="btn" value="提 交" />
                            </td>
                        </tr>
                    </table>

JQuery:

<script type="text/javascript">
    var maxCount = 200;  // 最高字数,这个值可以自己配置

    $("#doc").keyup(function () {
        var len = getStrLength(this.value);
        var lenCount = maxCount - len; //计算还可以输入多少个
        if (lenCount <0) {
            $(this).val($(this).val().substring(0, 200));
        }
        else {

            $("#count").html(lenCount);
        }
    })

    // 中文字符判断

    function getStrLength(str) {

        var len = str.length;

        var reLen = 0;

        for (var i = 0; i < len; i++) {

            if (str.charCodeAt(i) < 27 || str.charCodeAt(i) > 126) {

                // 全角     

                reLen += 2;

            } else {
                reLen++;
            }
        }

        return reLen;

    }
</script>

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。