寫了個限制文本框輸入最大長度的jquery插件 - jquery.restrictFieldLength.js


做了個限制文本框最大輸入長度的jquery插件,效果圖(共2個文本框,限制最多10個字符):

 

功能:當超出設置的最大字符長度后,會截斷字符串、更改當前元素的css(會在1秒后還原css)、支持長度超出后的異常回調

使用方式:

<body>
    <textarea id="filter1" rows="5" cols="100"></textarea>
    <textarea id="filter2" rows="5" cols="100"></textarea>
    <br />
    <span id="msg"></span>
    <script language="javascript" type="text/javascript">
        $(function () {
            function processException(id) {
                $("#msg").html(id + "&nbsp;exception occurred.<br />" + $("#msg").html());
            }

            $("#filter1,#filter2").restrictFieldLength({
                maxTextLength: 10,
                restoreTime:2000,
                exceptionCallback: processException
            });
        });
    </script>
</body>

 

jquery.restrictFieldLength.js:

(
    function ($) {
        $.fn.restrictFieldLength = function (settings) {
            var opts = $.extend({}, $.fn.restrictFieldLength.defaultSettings, settings || {});

            return this.each(function () {
                var elem = $(this);

                elem.on("keyup", function () {
                    var s = elem.val();
                    if (s.length >= opts.maxTextLength) {
                        elem.val(s.slice(0, opts.maxTextLength));
                        elem.prop("class", opts.exceptionCss);
                        if (opts.exceptionCallback) {
                            opts.exceptionCallback(elem[0].id);
                        }
                        var normalIt = function () {
                            elem.prop("class", opts.defaultCss);
                        }
                        setTimeout(normalIt, opts.restoreTime);
                    }
                });
            });
        }
        $.fn.restrictFieldLength.defaultSettings = {
            maxTextLength: 100,
            defaultCss: "restrictFieldLength_defaultCss",
            exceptionCss: "restrictFieldLength_exceptionCss",
            restoreTime:1000,
            exceptionCallback: null
        }
    }
)(jQuery);

 

jquery.restrictFieldLength.css

.restrictFieldLength_defaultCss
{
    color:black;
}
.restrictFieldLength_exceptionCss
{
    color:red;
}

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM