按下Enter键,专注于表格内的下一个输入字段 [英] Focus on next input field inside table with enter key press

查看:88
本文介绍了按下Enter键,专注于表格内的下一个输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Enter键进入具有很多行的表中的下一个输入字段.我尝试这个:

I need to move in to the next input field inside a table with many rows using enter key press. I try this :

$(function() {

    $('input').keyup(function (e) {
       if (e.which == 13) {
       $(this).find().next('input').focus();
       }
     });

});

为什么不工作? :(

HTML

<table class="half">
  <tr>
  <td>Nome :</td>
  <td><input name="ragsoc" type="text" id="ragsoc" value=""/></td>
  <td>Mnemo:</td>
  <td><input name="mnemo" type="text" id="mnemo" value=""/></td>
  <td>Partita IVA :</td>
  <td><input name="piva" type="text" id="piva" value=""/></td>
  </tr>
  <tr>
  <td>Nome :</td>
  <td><input name="ragsoc" type="text" id="ragsoc" value=""/></td>
  <td>Mnemo:</td>
  <td><input name="mnemo" type="text" id="mnemo" value=""/></td>
  <td>Partita IVA :</td>
  <td><input name="piva" type="text" id="piva" value=""/></td>
  </tr>
 </table>

此代码可以正常工作,但仅在表的第一行:

This code work fine but only in the first row of table :

$('input').keydown(function (e) {
    if (e.which === 13) {
    $(this).closest('td').nextAll().eq(1).find('input').focus()
    }
 });

出什么问题或遗漏了什么?

What is wrong or missing ?

推荐答案

假定.inputs是当前元素的同级元素. .find()搜索当前元素的后代(this)

Assuming .inputs is a sibling of your current element. .find() searches in descendants of current element(this)

 $('.inputs').keydown(function (e) {
    if (e.which === 13) {
       $(this).next('.inputs').focus();
    }
 });

您需要使用> .closest() .nextAll()

You need to use .closest(), .nextAll()

 $('.inputs').keydown(function (e) {
    if (e.which === 13) {
        $(this).closest('td').nextAll().eq(1).find('.inputs').focus();

        //OR
        //$(this).closest('td').next().next().find('.inputs').focus()
    }
 });

演示

OP已更新问题.使用

As OP has updated question. Use

 $('.inputs').keydown(function (e) {
     if (e.which === 13) {
         var index = $('.inputs').index(this) + 1;
         $('.inputs').eq(index).focus();
     }
 });

演示 ,请注意,我已经使用了class="inputs"

这篇关于按下Enter键,专注于表格内的下一个输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆