How to:Set Maxlength of Textarea using jQuery/JavaScript

文章源自:http://viralpatel.net/blogs/set-maxlength-of-textarea-input-using-jquery-javascript/

How to:Set Maxlength of Textarea using jQuery/JavaScript

Update: The maxlength plugin is now managed at GitHub. Please contribute to make this plugin more awesome.
GitHub: https://github.com/viralpatel/jquery.maxlength

Setting up maxlength of input text are easy. Just an attribute maxlength="##" does the work. But maxlength attribute does not work with textarea. I tried writing <textarea rows=”5″ cols=”30″ maxlength=”120″></textarea> but this does not works.

So what to do if we want to fix the maxlength of a textarea?

Use following jQuery plugin for setting maxlength of any textarea on your page.

First thing for doing is to add maxlength="XX" attribute in your <textarea> tag.

<textarea maxlength="15" rows="5" cols="30" name="address"></textarea>

 Include the jQuery plugin javascript file in your html page where the textarea is.

<script language="javascript" src="jquery.maxlength.js"></script>

 And, add following code snippet at the end of your html page.

<script type="text/javascript">
    jQuery(document).ready(function($) {
             //Set maxlength of all the textarea (call plugin)
             $().maxlength();
    })
</script>

 That’s it.. This jQuery plugin will search every textarea on your page and restrict the user to enter text till the maxlength.

Following is the code of plugin

/*
 * jQuery Maxlength plugin 1.0.0
 *
 * Copyright (c) 2013 Viral Patel
 * http://viralpatel.net
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 */
 
;(function ($) {
 
    $.fn.maxlength = function(){
          
        $("textarea[maxlength], input[maxlength]").keypress(function(event){
            var key = event.which;
              
            //all keys including return.
            if(key >= 33 || key == 13 || key == 32) {
                var maxLength = $(this).attr("maxlength");
                var length = this.value.length;
                if(length >= maxLength) {                    
                    event.preventDefault();
                }
            }
        });
    }
 
})(jQuery);

相关推荐