0

I ran into another problem with JS created inputs. I want the input to focus on the next one as soon, as it gets filled. So I write a number -> boom I'm on another input. I found this code, already posted on StackOverflow:

var inputs = $(':input').keypress(function(e){ 
    if (e.which == 13) {
       e.preventDefault();
       var nextInput = inputs.get(inputs.index(this) + 1);
       if (nextInput) {
          nextInput.focus();
       }
    }
});

Which I edited to:

var inputs = $(':input').keypress(function(e){ 
   var nextInput = inputs.get(inputs.index(this) + 1);
   if (nextInput) {
      nextInput.focus();
   }
});

It works fine. Until I ad new inputs with JS createElement() function. Then it always stops on the last input that was on the page right after load.

Any solutions? You can follow my work here.

Thanks!

David Stančík
  • 330
  • 3
  • 23
  • You can use just `static-ascendant :input` instead of only `:input`..! – Rohit Sharma Jan 10 '18 at 09:27
  • If you've already included jQuery then it's much easier to use that to create/clone your new elements. To solve your actual problem use a delegated event handler to attach the `keypress` event. See the duplicate for how to do that – Rory McCrossan Jan 10 '18 at 09:29

1 Answers1

0

Because when you call $(':input').keypress(); The input (that you create by the JS method createElement()) was not created yet so of course it will not have the keypress event.

There are some solutions for you. The easiest way is use delegated event handler. You can see how to use it here

Thank to the feed back of @Rory McCrossan

Vũ Nhật Anh
  • 424
  • 3
  • 14