简体   繁体   中英

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

I have the following 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>

If the user is in input 'a' and presses the tab key, I have it working now that the focus goes to input 'b'. However, once the user tabs while in input 'b', nothing happens. I would like jQuery to skip the select field 'c' and focus input 'd'.

Right now I use this and it works fine but it permits the user to tab the select into focus...instead i want it to ignore the select and try and focus the input in the tr and td after it:

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

您可以在标签索引中使用-1将其从订单中删除。

<select tabindex="-1">

In order to traverse all text inputs with TAB key a solution is:

 $(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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM