Skip to content

Instantly share code, notes, and snippets.

@davidwaterston
Created October 21, 2012 16:54
Show Gist options
  • Select an option

  • Save davidwaterston/3927588 to your computer and use it in GitHub Desktop.

Select an option

Save davidwaterston/3927588 to your computer and use it in GitHub Desktop.
jQuery: Add 'maxlength' support to textarea fields. Validates cleanly in JSLint.
(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));
@davidwaterston
Copy link
Copy Markdown
Author

Replaced 'bind' with on to allow delegation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment