Skip to content

Instantly share code, notes, and snippets.

@BRMatt
Created April 8, 2010 14:40
Show Gist options
  • Select an option

  • Save BRMatt/360132 to your computer and use it in GitHub Desktop.

Select an option

Save BRMatt/360132 to your computer and use it in GitHub Desktop.
jQuery.fn.limitMaxlength = function(options){
settings = jQuery.extend({
attribute: "maxlength",
onInit: function(){},
onLimit: function(){},
onEdit: function(){}
}, options);
// Event handler to limit the textarea
var onEdit = function(){
var textarea = jQuery(this);
var maxlength = parseInt(textarea.attr('maxlength'));
if(textarea.val().length > maxlength){
textarea.val(textarea.val().substr(0, maxlength));
jQuery.proxy(settings.onLimit, this)();
}
jQuery.proxy(settings.onEdit, this)();
}
this.each(settings.onInit);
return this.keyup(onEdit)
.focus(onEdit)
.focusout(onEdit);
}
$(document).ready(function(){
var onEditCallback = function(){
var length = $(this).val().length;
var maxlength = parseInt($(this).attr('maxlength'));
$(this)
.siblings('#charsRemaining')
.text('Characters remaining ' + (maxlength-length));
}
$('textarea[maxlength]').limitMaxlength({
onInit: onEditCallback,
onEdit: onEditCallback,
});
});
@SilviaIenciu
Copy link
Copy Markdown

Hi, can you please license this code of yours?
Thanks

@BRMatt
Copy link
Copy Markdown
Author

BRMatt commented Oct 27, 2020

@Silvialenciu You have my permission to copy, use, modify, or redistribute the code in any way without attributing me.

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