Search code examples
htmljqueryjquery-selectors

Jquery focus on next element with class


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

Solution

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