2

I am trying to create a function that when key press Enter occurs the next input with a class is selected.

I have managed to .focus() the next element within the same row. However, if I need to select the next input on the following row it fails to proceed.

The first .quantity textbox in the next row needs to be focused.

There is no error in console.

http://jsfiddle.net/FP6qa/

HTML

<table>
   <tr>
       <td>
         <input class='quantity' value=''/>
         <input class='100' value=''/>
       </td>
       <td>
         <input class='quantity' value=''/>
         <input class='50' value=''/>
       </td>
       <td>
         <input class='quantity' value=''/>
         <input class='20' value=''/>
       </td>
   </tr>
   <tr>
       <td>
         <input class='quantity' value=''/>
         <input class='100' value=''/>
       </td>
       <td>
         <input class='quantity' value=''/>
         <input class='50' value=''/>
       </td>
       <td>
         <input class='quantity' value=''/>
         <input class='20' value=''/>
       </td>
   </tr>
</table>

JQuery

 $(".quantity").on('keypress', function (e) {
        if (e.keyCode === 13) {
           $(this).parent().next('td').find('input.quantity').focus();
        }  
});
Jonas
  • 121,568
  • 97
  • 310
  • 388
JS1986
  • 1,920
  • 4
  • 29
  • 50

1 Answers1

9

You can use index method:

var $quan = $('.quantity');
$quan.on('keyup', function(e) {
    if (e.which === 13) {
        var ind = $quan.index(this);
        $quan.eq(ind + 1).focus()
    }
});

http://jsfiddle.net/cwgZP/

Or if you want to select all the inputs you can try:

var $input = $('input[type=text]');
$input.on('keyup', function(e) {
    if (e.which === 13) {
        var ind = $input.index(this);
        $input.eq(ind + 1).focus()
    }
});  
Ram
  • 143,282
  • 16
  • 168
  • 197
  • 1
    +1. That first method worked out almost exactly the same as what I was going to post (except I was going to do `var $quantity = $('.quantity').on(...` in one line). You even changed `keyCode` to `which` like I planned to... – nnnnnn Nov 12 '12 at 04:14
  • @undefined The first solution worked a treat. However, because this is part of a form it submits on the keypress event, I added return false; but it did not suceed – JS1986 Nov 12 '12 at 04:20
  • @nnnnnn Thank-you, what a great coincidence. – Ram Nov 12 '12 at 04:21
  • 1
    @claw - I think forms submit on key _down_ don't they? If so it's too late to cancel on key _up..._ – nnnnnn Nov 12 '12 at 04:22