Skip to content

Instantly share code, notes, and snippets.

@enqtran
Last active May 5, 2017 04:11
Show Gist options
  • Save enqtran/2e163a5bac5b6c8ab352c41df147695c to your computer and use it in GitHub Desktop.
Save enqtran/2e163a5bac5b6c8ab352c41df147695c to your computer and use it in GitHub Desktop.
(function($){
$.fn.extend({
limit: function(limit,element) {
var interval, f;
var self = $(this);
$(this).focus(function(){
interval = window.setInterval(substring,100);
});
$(this).blur(function(){
clearInterval(interval);
substring();
});
substringFunction = "function substring(){ var val = $(self).val();var length = val.length;if(length > limit){$(self).val($(self).val().substring(0,limit));}";
if(typeof element != 'undefined')
substringFunction += "if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}"
substringFunction += "}";
eval(substringFunction);
substring();
}
});
})(jQuery);
/*---------------------------- Limiting MaLength for TextArea --------------------------*/
$('#mytext').limit('100', '#charsLeft');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment