Enterで次の項目へ移動させる

投稿日:2022-11-11 投稿者:PS カテゴリ:その他 タグ: , ,

<div id="sample">
  <input type="text" name="name">
  <input type="tel" name="su">
  <input type="tel" name="tan">
  <input type="tel" name="price" tabindex="-1">  <!-- タブ移動をスキップさせたい -->
  <input type="hidden" name="tax">               <!-- 非表示 -->
</div>
var contents = $('#sample');
contents
  .on('keyup', 'input', function(e){ // input での keyup 時の例
    var my = $(this),
        c = e.which ? e.which : e.keyCode;
    switch(c){
      case 13: // [Enter]
        var obj = contents.find("input"), // ... 移動対象のオブジェクト全体
            no = obj.index(my), // ............. 現在の順番
            nxt;
        do {
          no++; // ........................... 次のオブジェクトの順番
          if( no > obj.length ) no = 0; // ... 次のオブジェクトが無い場合、先頭
          nxt = obj.eq(no); // ............... 次の移動対象
        } while( nxt.is(':visible')===false || nxt.attr('tabindex')==='-1' );
        nxt.focus();
        break;
      }
    }
  )