1

I'm trying to get the index of an input between a set of inputs. Basically, I have a table that contains, on more than one row, many inputs.

Once the user press the "enter" button, while the input is focused, I need to jump to the next input field, as the "tab" key do.

I was following this accepted response, and this is what I've done so far: Fiddle

CODE

$(document).keypress(function(e){
    if( e.which == 13 && e.target.nodeName == 'INPUT'){
        var inputs = $("#inputsTable input.td_in");
        alert(inputs.index(this));
    }
});

as you can see, every time you focus an input and then press ENTER, the popup msg says "-1"..

What am I doing wrong? I've been struggling with this piece of code for an hour, and I'm giving up.


I found out that replacing this with e.target also works.

CODE

$(document).keypress(function(e){
    if( e.which == 13 && e.target.nodeName == 'INPUT'){
        var inputs = $("#inputsTable input.td_in");
        alert(inputs.index(e.target));
    }
});
Community
  • 1
  • 1
BeNdErR
  • 17,471
  • 21
  • 72
  • 103

2 Answers2

2

That's because this references the document, not your input.

Use .on(), and pass it an input.td_in selector:

$('#inputsTable').on('keypress', 'input.td_in', function (e) {
    if( e.which == 13 ) {
        var inputs = $("#inputsTable input.td_in");
        alert(inputs.index(this));
    }
});

P.S. You should probably cache that selector.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • thanks for your reply! I've found out that also using "e.target" instead of "this" works for my example. – BeNdErR Aug 05 '13 at 15:20
0
$(document).on('keypress', 'input', function (e) {
    if( e.which == 13 ){
        var inputs = $("#inputsTable input");
        var the_index = inputs.index(this);        
        inputs[the_index+1].focus();
    }    
});

http://jsfiddle.net/5DwHw/1/

carter
  • 5,074
  • 4
  • 31
  • 40