JQuery应用

1. 只能输入数字

    <script type="text/javascript">
        $(function() {
            $("#<%=txtNetOrderNo.ClientID %>").keypress(function(e) {
                return e.keyCode >= 46 && e.keyCode <= 57;
            });
        });
    </script>

 

2. 输入文本框时显示剩余字数

HTML:

<div>

JS:

<script type="text/javascript">
        //返回val的字节长度
        function getByteLen(val) {
            var len = 0;
            for (var i = 0; i < val.length; i++) {
                if (val[i].match(/[^\x00-\xff]/ig) != null) //全角
                    len += 2;
                else
                    len += 1;
            }
            return len;
        }

        //返回val在规定字节长度max内的值
        function getByteVal(val, max) {
            var returnValue = '';
            var byteValLen = 0;
            for (var i = 0; i < val.length; i++) {
                if (val[i].match(/[^\x00-\xff]/ig) != null)
                    byteValLen += 2;
                else
                    byteValLen += 1;

                if (byteValLen > max)
                    break;

                returnValue += val[i];
            }
            return returnValue;
        }

        $(function() {
            var _area = $('textarea#txtPrizeNote');
            var _info = _area.next();
            var _max = _area.attr('maxlength');
            var _val;
            _area.bind('keyup change', function() { //绑定keyup和change事件
                if (_info.find('span').size() < 1) {//避免每次弹起都会插入一条提示信息
                    _info.append(_max);
                }

                _val = $(this).val();
                _cur = getByteLen(_val);

                if (_cur == 0) {//当默认值长度为0时,可输入数为默认maxlength值
                    _info.text(_max);
                } else if (_cur < _max) {//当默认值小于限制数时,可输入数为max-cur
                    _info.text(_max - _cur);
                } else {//当默认值大于等于限制数时
                    _info.text(0);

                    $(this).val(getByteVal(_val,_max)); //截取指定字节长度内的值
                }
            });
        });
    </script>

posted @ 2011-11-25 09:53    阅读(181)  评论(0编辑  收藏  举报