81

Enter キーを押すとフォーカスがページ上の「次の」フォーム要素に移動するフォームを作成しようとしています。私がウェブ上で見つけ続けている解決策は...

 <body onkeydown="if(event.keyCode==13){event.keyCode=9; return event.keyCode}">

残念ながら、これは IE でしか機能しないようです。したがって、この質問の真髄は、誰かが FF と Chrome で機能するソリューションを知っているかどうかです。さらに、フォーム要素自体にonkeydownイベントを追加する必要はありませんが、それが唯一の方法である場合は、追加する必要があります。

この問題は質問 905222に似ていますが、私の意見では独自の質問に値します。

編集: また、ユーザーが慣れ親しんでいるフォームの動作から逸脱しているため、これは良いスタイルではないという問題を提起する人もいます。同意します!お客様からのリクエストです:(

4

23 に答える 23

95

アンドリューが提案した非常に効果的なロジックを使用しました。そして、これは私のバージョンです:

$('body').on('keydown', 'input, select', function(e) {
    if (e.key === "Enter") {
        var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
        focusable = form.find('input,a,select,button,textarea').filter(':visible');
        next = focusable.eq(focusable.index(this)+1);
        if (next.length) {
            next.focus();
        } else {
            form.submit();
        }
        return false;
    }
});

KeyboardEvent のキーコード (つまり: e.keycode) 減価償却の通知:- https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

于 2012-08-26T13:24:36.330 に答える
18

[Enter] キーを [Tab] キーのように機能するようにマップする

Andre Van Zuydamの回答を書き直しましたが、これはうまくいきませんでした。jQuery で。EnterこれはとShift+の両方をキャプチャしEnterます。 Enterタブで進み、Shift+Enterタブで戻ります。

selfまた、現在フォーカスされているアイテムによって初期化される方法も書き直しました。フォームもそのように選択されます。コードは次のとおりです。

// Map [Enter] key to work like the [Tab] key
// Daniel P. Clark 2014

// Catch the keydown for the entire document
$(document).keydown(function(e) {

  // Set self as the current item in focus
  var self = $(':focus'),
      // Set the form by the current item in focus
      form = self.parents('form:eq(0)'),
      focusable;

  // Array of Indexable/Tab-able items
  focusable = form.find('input,a,select,button,textarea,div[contenteditable=true]').filter(':visible');

  function enterKey(){
    if (e.which === 13 && !self.is('textarea,div[contenteditable=true]')) { // [Enter] key

      // If not a regular hyperlink/button/textarea
      if ($.inArray(self, focusable) && (!self.is('a,button'))){
        // Then prevent the default [Enter] key behaviour from submitting the form
        e.preventDefault();
      } // Otherwise follow the link/button as by design, or put new line in textarea

      // Focus on the next item (either previous or next depending on shift)
      focusable.eq(focusable.index(self) + (e.shiftKey ? -1 : 1)).focus();

      return false;
    }
  }
  // We need to capture the [Shift] key and check the [Enter] key either way.
  if (e.shiftKey) { enterKey() } else { enterKey() }
});

理由textarea

含まれているのは、タブで移動たいからです。Enterまた、いったん入ったら、新しい行を挿入するというデフォルトの動作を止めたくありません。

その理由abutton

デフォルトのアクションを許可し、"" が引き続き次の項目にフォーカスするのは、常に別のページをロードするとは限らないためです。アコーディオンやタブ付きコンテンツなどにトリガー/エフェクトが存在する可能性があります。したがって、デフォルトの動作をトリガーし、ページがその特別な効果を発揮すると、トリガーが十分に導入されている可能性があるため、次の項目に移動する必要があります。

于 2014-12-18T11:21:33.293 に答える
6

ここに示したすべての実装には問題があります。テキストエリアと送信ボタンで適切に動作しないものもあれば、シフトを使用して前に戻ることを許可しないものもあり、タブインデックスを使用していてもタブインデックスを使用するものはなく、最後から最初または最初にラップアラウンドするものもありません最後まで。

[enter] キーを [tab] キーのように機能させながら、テキスト領域と送信ボタンで適切に機能させるには、次のコードを使用します。さらに、このコードを使用すると、シフト キーを使用して後方に移動でき、タブは前後および前後にラップします。

ソースコード: https://github.com/mikbe/SaneEnterKey

コーヒースクリプト

mbsd_sane_enter_key = ->
  input_types = "input, select, button, textarea"
  $("body").on "keydown", input_types, (e) ->
    enter_key = 13
    tab_key = 9

    if e.keyCode in [tab_key, enter_key]
      self = $(this)

      # some controls should just press enter when pressing enter
      if e.keyCode == enter_key and (self.prop('type') in ["submit", "textarea"])
        return true

      form = self.parents('form:eq(0)')

      # Sort by tab indexes if they exist
      tab_index = parseInt(self.attr('tabindex'))
      if tab_index
        input_array = form.find("[tabindex]").filter(':visible').sort((a,b) -> 
          parseInt($(a).attr('tabindex')) - parseInt($(b).attr('tabindex'))
        )
      else
        input_array = form.find(input_types).filter(':visible')

      # reverse the direction if using shift
      move_direction = if e.shiftKey then -1 else 1
      new_index = input_array.index(this) + move_direction

      # wrap around the controls
      if new_index == input_array.length
        new_index = 0
      else if new_index == -1
        new_index = input_array.length - 1

      move_to = input_array.eq(new_index)
      move_to.focus()
      move_to.select()

      false

$(window).on 'ready page:load', ->
  mbsd_sane_enter_key()

JavaScript

var mbsd_sane_enter_key = function() {
  var input_types;
  input_types = "input, select, button, textarea";

  return $("body").on("keydown", input_types, function(e) {
    var enter_key, form, input_array, move_direction, move_to, new_index, self, tab_index, tab_key;
    enter_key = 13;
    tab_key = 9;

    if (e.keyCode === tab_key || e.keyCode === enter_key) {
      self = $(this);

      // some controls should react as designed when pressing enter
      if (e.keyCode === enter_key && (self.prop('type') === "submit" || self.prop('type') === "textarea")) {
        return true;
      }

      form = self.parents('form:eq(0)');

      // Sort by tab indexes if they exist
      tab_index = parseInt(self.attr('tabindex'));
      if (tab_index) {
        input_array = form.find("[tabindex]").filter(':visible').sort(function(a, b) {
          return parseInt($(a).attr('tabindex')) - parseInt($(b).attr('tabindex'));
        });
      } else {
        input_array = form.find(input_types).filter(':visible');
      }

      // reverse the direction if using shift
      move_direction = e.shiftKey ? -1 : 1;
      new_index = input_array.index(this) + move_direction;

      // wrap around the controls
      if (new_index === input_array.length) {
        new_index = 0;
      } else if (new_index === -1) {
        new_index = input_array.length - 1;
      }

      move_to = input_array.eq(new_index);
      move_to.focus();
      move_to.select();
      return false;
    }
  });
};

$(window).on('ready page:load', function() {
  mbsd_sane_enter_key();
}
于 2014-11-12T19:48:18.760 に答える
4

OP ソリューションを Knockout バインディングに作り直したので、共有したいと思います。どうもありがとう :-)

ここにフィドルがあります

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js" type="text/javascript"></script>


</head>
<body>

    <div data-bind="nextFieldOnEnter:true">
        <input type="text" />
        <input type="text" />
        <select>
          <option value="volvo">Volvo</option>
          <option value="saab">Saab</option>
          <option value="mercedes">Mercedes</option>
          <option value="audi">Audi</option>
        </select>
        <input type="text" />
        <input type="text" />
    </div>


    <script type="text/javascript">
    ko.bindingHandlers.nextFieldOnEnter = {
        init: function(element, valueAccessor, allBindingsAccessor) {
            $(element).on('keydown', 'input, select', function (e) {
                var self = $(this)
                , form = $(element)
                  , focusable
                  , next
                ;
                if (e.keyCode == 13) {
                    focusable = form.find('input,a,select,button,textarea').filter(':visible');
                    var nextIndex = focusable.index(this) == focusable.length -1 ? 0 : focusable.index(this) + 1;
                    next = focusable.eq(nextIndex);
                    next.focus();
                    return false;
                }
            });
        }
    };

    ko.applyBindings({});
    </script>
</body>
</html>
于 2013-04-11T22:56:04.617 に答える
4

この動作を変更すると、実際には、ネイティブに実装されているデフォルトの動作よりもはるかに優れたユーザー エクスペリエンスが作成されます。ユーザーの観点から見ると、Enter キーの動作はすでに矛盾していると考えてください。1 行の入力では、Enter キーはフォームを送信する傾向がありますが、複数行のテキストエリアでは、単に改行をコンテンツに追加するだけだからです。分野。

私は最近、次のようにしました(jQueryを使用):

$('input.enterastab, select.enterastab, textarea.enterastab').live('keydown', function(e) {
 if (e.keyCode==13) {
  var focusable = $('input,a,select,button,textarea').filter(':visible');
  focusable.eq(focusable.index(this)+1).focus();
  return false;
 }
});

これは非常に効率的ではありませんが、十分に機能し、信頼性があります。このように動作する入力要素に「enterastab」クラスを追加するだけです。

于 2010-10-04T16:17:56.333 に答える
2

これは、他の回答をインスピレーションとして使用して、入力を次のフィールドに移動させる angular.js ディレクティブです。angular にパッケージ化された jQlite のみを使用しているため、ここにはおそらく奇妙に見えるコードがいくつかあります。ここにある機能のほとんどは、すべてのブラウザー > IE8 で動作すると思います。

angular.module('myapp', [])
.directive('pdkNextInputOnEnter', function() {
    var includeTags = ['INPUT', 'SELECT'];

    function link(scope, element, attrs) {
        element.on('keydown', function (e) {
            // Go to next form element on enter and only for included tags
            if (e.keyCode == 13 && includeTags.indexOf(e.target.tagName) != -1) {
                // Find all form elements that can receive focus
                var focusable = element[0].querySelectorAll('input,select,button,textarea');

                // Get the index of the currently focused element
                var currentIndex = Array.prototype.indexOf.call(focusable, e.target)

                // Find the next items in the list
                var nextIndex = currentIndex == focusable.length - 1 ? 0 : currentIndex + 1;

                // Focus the next element
                if(nextIndex >= 0 && nextIndex < focusable.length)
                    focusable[nextIndex].focus();

                return false;
            }
        });
    }

    return {
        restrict: 'A',
        link: link
    };
});

pdk-next-input-on-enter要素にディレクティブを追加するだけで、作業中のアプリでそれを使用する方法を次に示します。バーコード スキャナーを使用してフィールドにデータを入力しています。スキャナーのデフォルトの機能はキーボードをエミュレートし、スキャンしたバーコードのデータを入力した後に Enter キーを挿入することです。

このコードには副作用が 1 つあります (私のユースケースではプラスの効果です)。フォーカスをボタンに移動すると、enter keyup イベントによってボタンのアクションがアクティブになります。マークアップの最後のフォーム要素は、バーコードをスキャンしてすべてのフィールドを「タブ」にした後にアクティブにしたいボタンであるため、これは私のフローでは非常にうまく機能しました。

<!DOCTYPE html>
<html ng-app=myapp>
  <head>
      <script src="angular.min.js"></script>
      <script src="controller.js"></script>
  </head>
  <body ng-controller="LabelPrintingController">
      <div class='.container' pdk-next-input-on-enter>
          <select ng-options="p for p in partNumbers" ng-model="selectedPart" ng-change="selectedPartChanged()"></select>
          <h2>{{labelDocument.SerialNumber}}</h2>
          <div ng-show="labelDocument.ComponentSerials">
              <b>Component Serials</b>
              <ul>
                  <li ng-repeat="serial in labelDocument.ComponentSerials">
                      {{serial.name}}<br/>
                      <input type="text" ng-model="serial.value" />
                  </li>
              </ul>
          </div>
          <button ng-click="printLabel()">Print</button>
      </div>
  </body>
</html>
于 2014-01-21T21:05:07.447 に答える
1

+テンキーを押して次のフィールドに移動したいという同様の問題がありました。今、私はあなたに役立つと思うライブラリをリリースしました。

PlusAsTab : テンキーのプラス キーをタブ キーに相当するものとして使用する jQuery プラグイン。

代わりにenter/が必要なので、オプションを設定できます。jQuery event.which demoで使用するキーを見つけます。

JoelPurra.PlusAsTab.setOptions({
  // Use enter instead of plus
  // Number 13 found through demo at
  // https://api.jquery.com/event.which/
  key: 13
});

// Matches all inputs with name "a[]" (needs some character escaping)
$('input[name=a\\[\\]]').plusAsTab();

PlusAsTab enter as tab demoで自分で試すことができます。

于 2012-02-17T12:15:23.473 に答える
1

これを試して...

$(document).ready(function () {
    $.fn.enterkeytab = function () {
        $(this).on('keydown', 'input,select,text,button', function (e) {
            var self = $(this)
              , form = self.parents('form:eq(0)')
              , focusable
              , next
            ;
            if (e.keyCode == 13) {
                focusable = form.find('input,a,select').filter(':visible');
                next = focusable.eq(focusable.index(this) + 1);
                if (next.length) {
                    //if disable try get next 10 fields
                    if (next.is(":disabled")){
                        for(i=2;i<10;i++){
                            next = focusable.eq(focusable.index(this) + i);
                            if (!next.is(":disabled"))
                                break;
                        }
                    }
                    next.focus();
                }
                return false;
            }
        });
    }
    $("form").enterkeytab();
});
于 2017-04-26T20:32:17.793 に答える
1
function return2tab (div)
{
    document.addEventListener('keydown', function (ev) {
        if (ev.key === "Enter" && ev.target.nodeName === 'INPUT') {

            var focusableElementsString = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable]';

            let ol= div.querySelectorAll(focusableElementsString);

            for (let i=0; i<ol.length; i++) {
                if (ol[i] === ev.target) {
                    let o= i<ol.length-1? ol[i+1]: o[0];
                    o.focus(); break;
                }
            }
            ev.preventDefault();
        }
    });
}
于 2021-01-11T13:18:52.503 に答える
0

可能であれば、これを再検討します。フォーム内で押すというデフォルトのアクションは<Enter>フォームを送信し、このデフォルトのアクション/予想される動作を変更するために行うことは、サイトのユーザビリティの問題を引き起こす可能性があります。

于 2009-06-18T09:26:24.893 に答える
0

私はそれをJavaScriptだけで動かしています。Firefox では keyCode を更新できないため、keyCode 13 をトラップして、keyCode 9 が押されたかのように、tabIndex によって強制的に次の要素にフォーカスすることしかできません。トリッキーな部分は、次の tabIndex を見つけることです。私はこれを IE8-IE10 と Firefox でのみテストしましたが、動作します:

function ModifyEnterKeyPressAsTab(event)
{
    var caller;
    var key;
    if (window.event)
    {
        caller = window.event.srcElement; //Get the event caller in IE.
        key = window.event.keyCode; //Get the keycode in IE.
    }
    else
    {
        caller = event.target; //Get the event caller in Firefox.
        key = event.which; //Get the keycode in Firefox.
    }
    if (key == 13) //Enter key was pressed.
    {
        cTab = caller.tabIndex; //caller tabIndex.
        maxTab = 0; //highest tabIndex (start at 0 to change)
        minTab = cTab; //lowest tabIndex (this may change, but start at caller)
        allById = document.getElementsByTagName("input"); //Get input elements.
        allByIndex = []; //Storage for elements by index.
        c = 0; //index of the caller in allByIndex (start at 0 to change)
        i = 0; //generic indexer for allByIndex;
        for (id in allById) //Loop through all the input elements by id.
        {
            allByIndex[i] = allById[id]; //Set allByIndex.
            tab = allByIndex[i].tabIndex;
            if (caller == allByIndex[i])
                c = i; //Get the index of the caller.
            if (tab > maxTab)
                maxTab = tab; //Get the highest tabIndex on the page.
            if (tab < minTab && tab >= 0)
                minTab = tab; //Get the lowest positive tabIndex on the page.
            i++;
        }
        //Loop through tab indexes from caller to highest.
        for (tab = cTab; tab <= maxTab; tab++)
        {
            //Look for this tabIndex from the caller to the end of page.
            for (i = c + 1; i < allByIndex.length; i++)
            {
                if (allByIndex[i].tabIndex == tab)
                {
                    allByIndex[i].focus(); //Move to that element and stop.
                    return;
                }
            }
            //Look for the next tabIndex from the start of page to the caller.
            for (i = 0; i < c; i++)
            {
                if (allByIndex[i].tabIndex == tab + 1)
                {
                    allByIndex[i].focus(); //Move to that element and stop.
                    return;
                }
            }
            //Continue searching from the caller for the next tabIndex.
        }

        //The caller was the last element with the highest tabIndex,
        //so find the first element with the lowest tabIndex.
        for (i = 0; i < allByIndex.length; i++)
        {
            if (allByIndex[i].tabIndex == minTab)
            {
                allByIndex[i].focus(); //Move to that element and stop.
                return;
            }
        }
    }
}

このコードを使用するには、html 入力タグに追加します。

<input id="SomeID" onkeydown="ModifyEnterKeyPressAsTab(event);" ... >

または、JavaScript の要素に追加します。

document.getElementById("SomeID").onKeyDown = ModifyEnterKeyPressAsTab;

その他の注意事項:

入力要素で機能するためにのみ必要でしたが、必要に応じて他のドキュメント要素に拡張できます。これには、getElementsByClassName が非常に役立ちますが、それはまったく別のトピックです。

制限は、allById 配列に追加した要素間のタブのみであるということです。HTML ドキュメントの外側にあるツールバーやメニューなど、ブラウザーで使用できる他のものにタブで移動することはありません。おそらく、これは制限ではなく機能です。必要に応じて、keyCode 9 をトラップすると、この動作がタブ キーでも機能します。

于 2013-03-17T12:57:54.307 に答える
0

Mozilla、IE、および Chrome でテストされた以下のコードを使用できます

   // Use to act like tab using enter key
    $.fn.enterkeytab=function(){
         $(this).on('keydown', 'input, select,', function(e) {
        var self = $(this)
          , form = self.parents('form:eq(0)')
          , focusable
          , next
          ;
            if (e.keyCode == 13) {
                focusable = form.find('input,a,select,button').filter(':visible');
                next = focusable.eq(focusable.index(this)+1);
                if (next.length) {
                    next.focus();
                } else {
                    alert("wd");
                    //form.submit();
                }
                return false;
            }
        });

    }

使い方?

$("#form").enterkeytab(); // キータブに入る

于 2013-07-31T15:34:56.037 に答える
0

これが私が思いついたものです。

form.addEventListener("submit", (e) => { //On Submit
 let key = e.charCode || e.keyCode || 0 //get the key code
 if (key = 13) { //If enter key
    e.preventDefault()
    const inputs = Array.from(document.querySelectorAll("form input")) //Get array of inputs
    let nextInput = inputs[inputs.indexOf(document.activeElement) + 1] //get index of input after the current input
    nextInput.focus() //focus new input
}
}
于 2019-05-10T22:25:24.847 に答える
-1

私にも同様のニーズがありました。これが私がしたことです:

  <script type="text/javascript" language="javascript">
    function convertEnterToTab() {
      if(event.keyCode==13) {
        event.keyCode = 9;
      }
    }
    document.onkeydown = convertEnterToTab;    
  </script>  
于 2009-12-09T16:52:17.590 に答える
-2

フォーム要素をプログラムで繰り返し、onkeydown ハンドラーを追加することができます。このようにして、コードを再利用できます。

于 2009-06-17T22:23:57.783 に答える