码迷,mamicode.com
首页 > Web开发 > 详细

jQuery实现还能输入N字符

时间:2014-12-15 10:35:23      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:jquery实现特效   限制输入字符个数   

页面:

<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>

jQuery实现还能输入N字符

标签:jquery实现特效   限制输入字符个数   

原文地址:http://haihuiwei.blog.51cto.com/4789207/1589960

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!