首页 > 代码库 > jQuery实现还能输入N字符

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="http://www.mamicode.com/sitecn/images/face.jpg" /></div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                还能输入<span id="count"></span>字
                                <input type="button" class="btn" value="http://www.mamicode.com/提 交" />
                            </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>

jQuery实现还能输入N字符