webでもカーソル移動(jQuery版)

昨日のを、jQueryだとどう書くか試してみました。

  • prototype.jsの代わりにjquery.jsを使います。(バージョン:1.2.3)
  • 他は昨日のと同じ。


$(function() {
var val;
$("input").focus(function(){
if ($(this).attr("type") == "text") {
val = $(this).val();
}
});
$("input").keypress(function(e){
if ($(this).attr("type") == "text") {
m = eval($(this).attr("maxlength"));
if (m > 0) {
if (new String($(this).val()).length == m) {
if (e.which == 13) {
setNextEntryInput($(this));
}
}
}
}
});
$("input").keyup(function(){
if ($(this).attr("type") == "text") {
if ($(this).val() != val) {
m = eval($(this).attr("maxlength"));
if (m > 0) {
if (new String($(this).val()).length == m) {
setNextEntryInput($(this));
}
}
}
}
});

});

function setNextEntryInput(thisobj) {
var flg = false;
obj = $(thisobj);
do {
obj = $(obj).next();
if (obj) {
flg = true;
if ($(obj).attr("type") == "hidden") flg = false;
if ($(obj).attr("disabled") == true) flg = false;
if (flg == true) {
break;
}
}
} while (obj)
if (obj) {
$(obj).focus();
if (obj.attr("type") == "text") {
$(obj).select();
}
}
}

とりあえず動きます。
うーん。私はprototype.jsの方が好きかなー。ループはループになってる方が分かりやすい気がするんですよ。
e.whichとnext()は便利ですけどね。
でもform内にdivとかtableとか使ってると上手く動かないです。とにかくform内の次の入力項目、てどうやって取ればいいのか途方に暮れたので諦めました。
あと、changeイベントかkey関連のイベントで何かすれば、同じ内容を再入力したときもきちんと動作するようになるんだろうけど、そこまでしなくてもいいかなーとこちらも諦めました。