Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

jQuery.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();
            }
        }
    });
}
like image 414
Cam Avatar asked Feb 17 '10 05:02

Cam


1 Answers

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

like image 122
Doug Neiner Avatar answered Sep 28 '22 03:09

Doug Neiner