Enterキーを押下したとき、tabキーを押したときのように次の入力フォームへ移動させるためのスクリプトです。
ソース
// 移動先の対象 var targetElm = "input[type=text],input[type=password],input[type=submit],select,input[type=button],input[type=checkbox],textarea,a,button"; $targetElm = $( targetElm ); $(function () { var elements = "input[type=text],input[type=password],select,input[type=checkbox]"; $(elements).keypress(function (e) { var c = e.which ? e.which : e.keyCode; if (c == 13) { var tabindex = $( this ).attr( "tabindex" ); if( typeof( tabindex ) != "undefined" && $( "[tabindex='" + ( tabindex - 0 + 1 ) + "']" ).size() > 0 ){ $( "[tabindex='" + ( tabindex - 0 + 1 ) + "']" ).focus(); }else{ var index = $targetElm.index(this); $targetElm.eq( index + 1 ).focus(); } e.preventDefault(); } }); });
解説
// 移動先の対象 var targetElm = "input[type=text],input[type=password],input[type=submit],select,input[type=button],input[type=checkbox],textarea,a,button"; $targetElm = $( targetElm );
イベントが起った際、移動先となるターゲットをjquery型の変数へ保持します。
これ以外に、「:visible」を指定し、見えているものだけをターゲットにするのも良いかも知れませんが、速度が遅くなりました。
var elements = "input[type=text],input[type=password],select,input[type=checkbox]";
Enterをtabと扱うイベントを発生させる要素です。
ここで、「a」タグ、「button」タグなどは、Enterで決定イベントを実行させることが多いので、除外しています。
if( typeof( tabindex ) != "undefined" && $( "[tabindex='" + ( tabindex - 0 + 1 ) + "']" ).size() > 0 ){ $( "[tabindex='" + ( tabindex - 0 + 1 ) + "']" ).focus(); }else{
タブインデックスが定義してある場合の処理です。
本来であれば、タブインデックスが指定してあり次のものが無い場合は、「0」へ戻るのが良いかも知れませんが、私はこの方法がしっくりきます。
コメント