Skip to content

Instantly share code, notes, and snippets.

@nissuk
Created July 3, 2011 18:42
Show Gist options
  • Save nissuk/1062463 to your computer and use it in GitHub Desktop.
Save nissuk/1062463 to your computer and use it in GitHub Desktop.
jQuery: 分割されたテキストボックスをグループとして扱うプラグイン(実験的)
/**
* jQuery input group plugin (実験的)
* public domain
*
* 郵便番号、電話番号、シリアル番号などの分割されたテキストボックスを
* 1つのグループ化されたテキストボックスとして扱います。
* 具体的には下記の挙動を取ります。
*
* 1. 要素内にある入力項目にユーザーが文字を入力しており、その入力文字数が
* a. 指定文字数(maxlength)に達した場合、次の入力項目に移動します。
* b. 指定文字数のときに新たに文字が入力された場合、次の入力項目に移動し、
* 入力された文字を次の入力項目に入力します。
* (optionsにseparatorが指定されていて、入力された文字が
* separatorと同じ場合は入力項目の移動のみ)
* c. 0のときにバックスペースが押された場合、前の入力項目に移動します。
*
* # 使用方法
// * HTML:
* <div class="postal">
* <input type="text" name="postal-1" maxlength="3"
* />-<input type="text" name="postal-2" maxlength="4" />
* </div>
*
* JavaScript:
* $('div.postal').inputGroup({ separator: '-' });
*
* # TODO
* - 同じclass属性のついたテキストボックスのグループ化
*/
(function($){
var Keys = {};
Keys.Back = 8;
$.fn.inputGroup = function(options){
var settings = $.extend({}, $.fn.inputGroup.defaults, options);
return this.each(function(){
var box = $(this);
var inputs = box.find('input:text');
var handleBackspace = function(x){
var $this = $(x);
var maxlength = $this.attr('maxlength');
var text = $this.val();
if (text.length == 0) {
var index = inputs.index($this);
if (index == 0) return true;
var input = inputs.eq(index - 1);
// Opera(11.01)はバックスペースで文字を削除するタイミングが
// keydownイベント終了後になるようなので移動のタイミングをずらします。
setTimeout(function(){
input.focus();
var input0 = input[0];
// IEはfocus()するとキャレット位置が先頭になってしまうようなので
// キャレット位置を末尾にします。
if ('createTextRange' in input0) {
var range = input0.createTextRange();
range.move('character', input0.value.length);
range.select();
}
}, 1);
return false;
}
return true;
};
inputs
.keydown(function(e){
if (e.keyCode == Keys.Back) {
// バックスペースが押されたときkeydown, keypressの発動の組み合わせが
// ブラウザによってまちまちのため、
// keydownかkeypressのどちらかしか発動しないようにガードします。
$(window).data('bs-keydown', true);
return handleBackspace(this);
}
})
.keypress(function(e){
var $this = $(this);
var maxlength = $this.attr('maxlength');
var text = $this.val();
if (e.keyCode == Keys.Back) {
if (!$(window).data('bs-keydown')) {
return handleBackspace(this);
}
}
else if (maxlength <= text.length + 1) {
var index = inputs.index(this);
var c = String.fromCharCode(e.which);
var input = inputs.eq(index + 1);
// IEはコントロールに入力文字が入るタイミングが
// keypressイベント終了後になるようなので移動のタイミングをずらします。
setTimeout(function(){
input.focus();
if (c != settings.separator && maxlength < text.length + 1) {
input.val(c);
}
}, 1);
}
})
});
};
$.fn.inputGroup.defaults = {
separator: ''
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment