Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus on next input field inside table with enter key press

Tags:

jquery

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();
       }
     });

});

Why dont work ? :(

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 ?

like image 933
geomo Avatar asked Jan 20 '14 17:01

geomo


1 Answers

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();
    }
 });

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()
    }
 });

DEMO

As OP has updated question. Use

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

DEMO, As note I have used class="inputs"

like image 76
Satpal Avatar answered Oct 05 '22 12:10

Satpal