web-dev-qa-db-ja.com

現在の入力に値がある場合、次のフォーム入力に進む方法は?

たくさんのエントリがあるフォームを持っています。現在のテキストボックスに値を入力したら、次のテキストボックスにフォーカスを変更したいと思います。最後のフィールドまでこのプロセスを続けたいと思っています。私の質問は、テキストボックスに値を入力したら、Javascriptコーディングでタブキーを押すと何が起こるかをシミュレートすることです。

キーボードのタブキーを押さずに、Javascriptを介して同じ機能を提供したいと思います。これは可能ですか?

31
praveenjayapal

次の入力フィールドにフォーカスを与える必要があります(その入力要素でfocus()メソッドを呼び出します)。たとえば、jQueryを使用している場合、このコードはEnterキーが押されたときにタブキーをシミュレートします。

var inputs = $(':input').keypress(function(e){ 
    if (e.which == 13) {
       e.preventDefault();
       var nextInput = inputs.get(inputs.index(this) + 1);
       if (nextInput) {
          nextInput.focus();
       }
    }
});
43
krcko

少し前にタブ機能をエミュレートする必要がありましたが、今では ライブラリとしてリリースjquery を使用しています。

EmulateTab :ページ上の要素間のタブ移動をエミュレートするjQueryプラグイン。

デモでの動作を確認

if (myTextHasBeenFilledWithText) {
  // Tab to the next input after #my-text-input
  $("#my-text-input").emulateTab();
}
18
Joel Purra
function nextField(current){
    for (i = 0; i < current.form.elements.length; i++){
        if (current.form.elements[i].tabIndex == current.tabIndex+1){
            current.form.elements[i].focus();
            if (current.form.elements[i].type == "text"){
                current.form.elements[i].select();
            }
        }
    }
}

これは、現在のフィールドで提供されると、次のタブインデックスを持つフィールドにフォーカスをジャンプします。使用法は次のようになります

<input type="text" onEvent="nextField(this);" />
13
Gausie

これにより、フォーム内のタブがシミュレートされ、Enterキーが押されたときに次の入力にフォーカスが与えられます。

window.onkeypress = function(e) {
    if (e.which == 13) {
        e.preventDefault();
        var inputs = document.getElementsByClassName('input');
        for (var i = 0; i < inputs.length; i++) {
        if (document.activeElement.id == inputs[i].id && i+1 < inputs.length ) {
            inputs[i+1].focus();
            break;   
        }
    }
5
Zach M

私が望んでいたことをすることができる答えを見つけることができませんでした。ユーザーがタブ移動したくないリンク要素がいくつかあるという問題がありました。これは私が思いついたものです:

(自分のコードでは、a行でallElementsの代わりにa:not(.dropdown-item)を使用し、ユーザーがa.dropdown-item。)

function(event){
        //Note that this doesn't honour tab-indexes

        event.preventDefault();

        //Isolate the node that we're after
        const currentNode = event.target;

        //find all tab-able elements
        const allElements = document.querySelectorAll('input, button, a, area, object, select, textarea, [contenteditable]');

        //Find the current tab index.
        const currentIndex = [...allElements].findIndex(el => currentNode.isEqualNode(el))

        //focus the following element
        allElements[currentIndex + 1].focus();
}
5
Andrew Peters

最初の質問では、無駄になるすべての入力にイベントリスナーは必要ありません。

代わりに、Enterキーをリッスンし、現在フォーカスされている要素を見つけるには、document.activeElementを使用します

window.onkeypress = function(e) {
    if (e.which == 13) {
       e.preventDefault();
       var nextInput = inputs.get(inputs.index(document.activeElement) + 1);
       if (nextInput) {
          nextInput.focus();
       }
    }
};

特に低電力/モバイルブラウザでは、1つのイベントリスナが多くのイベントリスナよりも優れています。

2
mattdlockyer

これは動作するはずです。 tabindexを使用する場合と使用しない場合。

var currentlyFocused = undefined;
var tabableElements = undefined;

/**
 * Compare function for element sort
 * @param {string | null} a
 * @param {string | null} b
 * @param {boolean} asc
 */
function sortCompare(a, b, asc = true) {
  let result = null;
  if (a == null) result = 1;
  else if (b == null) result = -1;
  else if (parseInt(a) > parseInt(b)) result = 1;
  else if (parseInt(a) < parseInt(b)) result = -1;
  else result = 0;
  return result * (asc ? 1 : -1);
}

/**
 * When an element is focused assign it to the currentlyFocused variable
 * @param {Element} element
 */
function registerOnElementFocus(element) {
  element.addEventListener("focus", function(el) {
    currentlyFocused = el.srcElement;
  });
}

/**
 * Tab Trigger
 */
function onTabClick() {
  //Select currently focused element
  let currentIndex;
  tabableElements.forEach((el, idx) => {
    //return if no element is focused
    if (!currentlyFocused) return;
    if (currentlyFocused.isEqualNode(el)) {
      //assign current index and return
      currentIndex = idx;
      return;
    }
  });
  //if theres no focused element or the current focused element is last start over
  let lastIndex = tabableElements.length - 1;
  let nextElementidx = currentIndex === undefined || currentIndex == lastIndex ? 0 : currentIndex + 1;
  //Focus
  currentlyFocused = tabableElements[nextElementidx];
  currentlyFocused.focus();
}
/**
 * Init must be run after all elements are loadead in the dom
 */
function init() {
  //Get all tab-able elements
  let nodeList = document.querySelectorAll("input, button, a, area, object, select, textarea, [tabindex]");
  //To array for easier manipulation
  tabableElements = Array.prototype.slice.call(nodeList, 0);
  //Correcting tabindexes to ensure correct order
  tabableElements.forEach((el, idx, list) => {
    let tabindex = el.getAttribute("tabindex");
    //-1 tabindex will not receive focus
    if (tabindex == -1) list.splice(idx, 1);
    //null or 0 tabindex in normal source order
    else if (tabindex == null || tabindex == 0) {
      list[idx].setAttribute("tabindex", 9999 + idx);
    }
  });
  //sort elements by their tabindex in ascending order
  tabableElements.sort((elementA, elementB) => sortCompare(elementA.getAttribute("tabindex"), elementB.getAttribute("tabindex")));
  //register focus event to elements
  tabableElements.forEach(el => registerOnElementFocus(el));
}
<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

  <title>Virtual tab</title>
</head>

<body onload="init()">
  <div class="container">
    <h3>Virtual Tab Demo</h3>
    <form>
      <div class="btn btn-primary" style="position: fixed;" onclick="onTabClick()">
        Tab!
      </div>
      <br>
      <br>
      <button id="button1" type="button" onclick="alert('button 1')">Button1</button>
      <button id="button2" type="button" onclick="alert('button 2')">Button2</button>
      <br>
      <br>
      <input id="text" type='text'>text
      <br>
      <input id="password" type='password' tabindex="-1">password
      <br>
      <input id="number" type='number' tabindex="5">number
      <br>
      <input id="checkbox" type='checkbox'>checkbox
      <br>
      <input id="radio" type='radio'>radio
      <br>
      <br>
      <button id="button3" type="button" onclick="alert('button 3')">Button3</button>
      <button id="button4" type="button" onclick="alert('button 4')">Button4</button>
      <br>
      <br>
      <select id="select">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>
      <br>
      <br> textarea
      <br>
      <textarea id="textarea"></textarea>
        <br>
        <br>
        <span id="span" tabindex="1">Focus other elements.</span>
    </form>
  </div>
  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>

</html>