Created
October 21, 2012 16:54
-
-
Save davidwaterston/3927588 to your computer and use it in GitHub Desktop.
jQuery: Add 'maxlength' support to textarea fields. Validates cleanly in JSLint.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (function ($) { | |
| 'use strict'; | |
| $.textareaMaxlength = function () { | |
| // Allows the 'maxlength' attribute to be used with textarea fields to limit the | |
| // number of characters that can be entered. | |
| // e.g <textarea id="myfield" maxlength="250"></textarea> | |
| // jsFiddle: http://jsfiddle.net/davidwaterston/DdxCQ | |
| $(document).on('keyup input paste', 'textarea[maxlength]', function () { | |
| var maxlength = parseInt($(this).attr('maxlength'), 10), | |
| text = $(this).val(), | |
| textlength = text.length; | |
| if (textlength > maxlength) { | |
| $(this).val(text.substr(0, maxlength)); | |
| } | |
| }); | |
| }; | |
| }(jQuery)); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Replaced 'bind' with on to allow delegation.