<html> <head> <script type="text/javascript" src="/js/jquery-1.9.1.js"></script> <script type="text/javascript" src="/js/jquery.limit2.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#text").limita({ limit: 100, id_result: "counter", alertClass: "alert" }); }); </script> </head> <body> <form id="input_form" method="POST" action="?"> <textarea id="text" rows="4" cols="49"></textarea> <input type="submit" value="submit"> </form> <div id="counter"></div> </body> </html>
(function($){ $.fn.limita = function(options) { var defaults = { limit: 200, id_result: false, alertClass: false } var options = $.extend(defaults, options); return this.each(function() { var characters = options.limit; if(options.id_result != false) { $("#"+options.id_result).append("You have <strong>"+ characters+"</strong> characters"); } $(this).keyup(function(){ if($(this).val().length > characters){ $(this).val($(this).val().substr(0, characters)); } if(options.id_result != false) { var remaining = characters - $(this).val().length; $("#"+options.id_result).html("You have <strong>"+remaining+"</strong> characters"); if(remaining <= 10) { $("#"+options.id_result).addClass(options.alertClass); } else { $("#"+options.id_result).removeClass(options.alertClass); } } }); }); }; })(jQuery);
Last Updated on October 26, 2015