/*
*Length Tracker
*v2. 1.0
*bind2Id: ID of the element used to display length changes
*max: Maximum length
*msgWrap: Prompt message (must have a "-" placeholder)
*eg: $('#input').lenTracer({bind2Id:'myTracer',max:150,msgWrap:'You can also enter - characters'});
*author:liujg1015@gmail.com
* /
(function ($) {
var zw_validate = function (el, option) {
this.el = $(el);
this.bindEl = false;
this.setting = {
bind2Id: false,
max: 100,
msgWrap: 'You can also enter - characters'
};
if (option) {
$.extend( this.setting, option);
this.init();
}
};
zw_validate.prototype = {
init: function () {
var _this = this;
this.bindEl = $('#' this.setting.bind2Id);
this.el.focus(function () { _this.start(); }).blur(function () { _this.dispose (); });
this.el.css({ paddingBottom: 20 });
this.initMsg();
},
initMsg: function () {
var wrap = this.setting.msgWrap.split('-');
this.bindEl.text(this.setting.max - this.count().total).before(wrap[0]).after(wrap[ 1]);
},
count: function () {
var _val = this.el.val();
var _len = _val.length;
var _rowCount = 0;
var _enterLen = 0;
var _partten = /n /g;
if (_len > 0 && _partten.test(_val)) {
_enterLen = 3;
while (( result = _partten.exec(_val)) != null) {
if ((result.index 1 _enterLen) > this.setting.max) {
break;
}
_enterLen = 3 ;
}
_rowCount = _val.match(_partten).length;
}
return { total: (_len _rowCount * 3), enterLen: _enterLen };
},
start: function () {
var _this = this;
_this.timer = setInterval(function () {
var _val = _this.el.val();
var _rlt = _this.count ();
if (_rlt.total > _this.setting.max) {
if (_rlt.enterLen > 0) {
_this.el.val(_val.substr(0, _this. setting.max - _rlt.enterLen));
}
else {
_this.el.val(_val.substr(0, _this.setting.max));
}
_this .bindEl.text(_this.setting.max - _this.count().total);
return;
}
_this.bindEl.text(_this.setting.max - _rlt.total);
}, 300);
},
dispose: function () {
clearInterval(this.timer);
},
restore: function () {
this. bindEl.text(this.setting.max - this.el.val().length);
}
};
$.fn.extend({
lenTracer: function (option) {
return new zw_validate(this, option);
}
});
})(jQuery);
1. The above is a script for the counter, which can be Paste the script into a js file and add a reference in the html.
2. The above code shows how to use it.
This counter is written by myself using jQuery, so it depends on the jQuery library function. The carriage return character can be calculated because the carriage return character in the textarea is 'rn' after it is submitted to the background. Criticisms and corrections are welcome.