jQuery将输入集中在下一个tr->td时,td包含一个输入字段,但从不关注html选择

jQuery focus the input in the next tr -> td when that td contains an input field, but never focus html select

本文关键字:td 输入 字段 选择 html 包含一 集中 下一个 tr- gt jQuery      更新时间:2023-09-26

我有以下html:

<tr>
  <td>Name</td><td><input type="text" name="a"></td>
</tr>
<tr>
  <td>Address</td><td><input type="text" name="b"></td>
</tr>
<tr>
  <td>Type</td><td><select name="c"></td>
</tr>
<tr>
  <td>Gender</td><td><input type="text" name="d"></td>
</tr>

如果用户在输入"a"中并按下tab键,那么现在焦点转到输入"b",它就可以工作了。但是,一旦用户在输入'b'时进行制表,就不会发生任何事情。我希望jQuery跳过选择字段"c"和焦点输入"d"。

现在我使用它,它工作得很好,但它允许用户将选择标记到焦点。。。相反,我希望它忽略select,并尝试将tr和td中的输入集中在它之后:

$(this).closest('tr').next().find('input:text').first().focus();

您可以在选项卡索引中使用-1将其从订单中删除。

<select tabindex="-1">

为了使用TAB键遍历所有文本输入,解决方案是:

$(function () {
  $(':text').on('keydown', function (e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode == 9) { // on tab go to next input
      // prevent the default action
      e.preventDefault();
      
      // select the next row containing a text input field (skip select!)
      // and get the first element
      var nextInput = $(e.target).closest('tr').nextAll('tr').filter(function(index, element) {
        return $(element).find(':text').length > 0;
      }).first().find(':text');
      
      // if next input exists go there, else go to the first one
      if (nextInput.length == 0) {
        $(':text:first').focus();
      } else {
        nextInput.focus();
      }
    }
    return false;
  });
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<table>
    <tr>
        <td>Name</td>
        <td><input type="text" name="a"></td>
    </tr>
    <tr>
        <td>Adress</td>
        <td><input type="text" name="b"></td>
    </tr>
    <tr>
        <td>Type</td>
        <td><select name="c"></td>
    </tr>
    <tr>
        <td>Gender</td>
        <td><input type="text" name="d"></td>
    </tr>
</table>