■ 入力文字数の制限を可視化する JavaScript
好評の、読み込ませるだけシリーズ の8番目。
maxlength 属性とかアプリケーション側とかでフォームの入力文字数を制限していても、ユーザにとっては自分が何文字くらい入力したかがわからないと不便そうなので、汎用的なのを作りました。
フォームにフォーカスが当たると、入力した文字数と入力可能な文字数が表示され、リアルタイムに更新されていきます。
コードは次の通りでして、prototype.js(1.5.0くらい) に依存してます。
var VisualLength = Class.create();
VisualLength.prototype = {
initialize: function(attribute) {
this.fields = ['INPUT', 'TEXTAREA'];
this.attribute = attribute || 'maxlength';
this.ignore = '__'+this.attribute;
this.scan();
this.create();
},
create: function() {
this.box = Element.extend(document.createElement('div'));
this.box.setStyle({ position: 'absolute', backgroundColor: '#FFF', border: '1px solid #DDD', display: 'none' });
document.body.appendChild(this.box);
},
show: function(e) {
this.target = Event.element(e);
this.max = this.target.getAttribute(this.attribute);
this.checker();
Position.clone(this.target, this.box);
var top = parseInt(this.box.style.top) - 30;
this.box.setStyle({ width: '5em', height: '1.5em', top: top+'px' });
this.box.show();
},
hide: function() {
this.box.hide();
},
checker: function() {
var len = this.target.value.length;
if(len > this.max)
len = '<font color="red">'+len+'</font>';
this.box.innerHTML = len + '/' + this.max;
},
scan: function(parent) {
parent = parent || document;
for(var t, i = 0; t = this.fields[i]; i++) {
this.parse(parent.getElementsByTagName(t));
}
},
parse: function(elms) {
for(var elm, i = 0; elm = elms[i]; i++) {
if(elm.getAttribute(this.attribute)) {
if(elm.getAttribute(this.ignore)) continue;
Event.observe(elm, 'focus', this.show.bind(this));
Event.observe(elm, 'blur', this.hide.bind(this));
Event.observe(elm, 'keydown', this.checker.bind(this));
Event.observe(elm, 'keyup', this.checker.bind(this));
elm.setAttribute(this.ignore, 'true');
}
}
}
};
ここまでが共通部分で、window.onload のタイミングとかで new VisualLength してやるだけで、HTML 内の maxlength 属性がついてる要素をいじってくれます。
Event.observe(window, 'load', function() {
new VisualLength();
});
maxlength 属性を使いたくない場合には、VisualLength の引数に任意の属性を指定すれば大丈夫。
Event.observe(window, 'load', function() {
new VisualLength('length');
});
動的に要素を追加したりする場合も考慮してまして、そんな場合は VisualLength#scan を手動で実行すればいいんだけど…。サンプル作るのめんどうなのでコード読んで下さい、すいません。
文字数の取得タイミングは keyup, down でうまく取れるかあんまり検証してないので、あとで変えるかもしれません。タイマー使った処理が綺麗に書けそうなら、それもいいかな。 あと、なんか見た目がシンプル過ぎて逆にわかりにくくなりそうなので、見栄えもいじるかも。
Posted by Kyosuke Takayama at 2007-07-03 (Tue) 18:46 printable version


○ Bugle Diary: [javascript]文字数カウント like twitter (2008-09-09 (Tue) 22:45) 0%