开发者

Maxlength in textarea using jQuery

Using the script off http://viralpatel.net/blogs/2008/12/set-maxlength-of-textarea-input-using-jquery-javascript.html I am trying to limit the input of a textarea to 1000 characters. Prototype is also included in the page.

It works fine in chrome, but in firefox the following error is given and the input is not limited:

$("textarea[maxlength]") is null

I'm completely stumped. Any help would be appreciated. The code snippets follow.

The textarea:

<%= text_area 'project', 'description', 'cols' => 60, 'rows' => 8, 'maxlength' => 1000 %>

The javascript:

<%= javascript_include_tag "jquery", "jquery.maxlength" -%>
<script type="text/javascript">
  jQuery.noConflict();
  jQuery(document).ready(function($) {
    $().maxlength();
  })
</script>

jquery.maxlength.js:

jQ开发者_如何学编程uery.fn.maxlength = function(){
    $('textarea[maxlength]').keypress(function(event){
        var key = event.which;
        //all keys including return.
        if(key >= 33 || key == 13) {
            var maxLength = $(this).attr('maxlength');
            var length = this.value.length;
            if(length >= maxLength) {
                event.preventDefault();
            }
        }
    });
}


Wrap your jquery.maxlength.js file in this:

(function($){
   .. existing code goes here
})(jQuery);

When you call $().maxlength() it is trying to use the $ variable, but in a different scope and it no longer is equal to jQuery. By wrapping the plugin in a self executing anonymous function, it creates a private scope where $ = jQuery


Since jQuery is set to noConflict() mode you need to change jquery.maxlength.js to

(function($)
    $.fn.maxlength = function(){
        $('textarea[maxlength]').keypress(function(event){
            var key = event.which;
            //all keys including return.
            if(key >= 33 || key == 13) {
                var maxLength = $(this).attr('maxlength');
                var length = this.value.length;
                if(length >= maxLength) {
                    event.preventDefault();
                }
            }
        });
    };
})(jQuery);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜