Search code examples
jqueryajaxkeypress

jquery on ready keypressed


My page have elements loaded with ajax, i need use enter to go next input, textarea or select. some inputs have a function to format numbers but the solution above run more that once.

$(document).on('keypress',function(){
    var inputs = $('input, select, textarea').on("keypress", function(e) {
    if (e.which == 13) {
        if ($(this).attr('data-format')) {
            formatNumber($(this));
        }
        e.preventDefault();
        var nextInput = inputs.get(inputs.index(this) + 1);
        if (nextInput) {
            nextInput.focus();
        }
    }
});
});

Solution

  • As Rory and Jason mentioned, you're probably looking for event delegation. This will allow any new inputs that didn't initially exist still respond to the keypress event once they appear. Here's a good article on the subject: https://learn.jquery.com/events/event-delegation/ and your code should look something like this:

    UPDATE:

    $(document).on('keypress', 'input, select, textarea', function(e){
    
      var inputs = $("input, select, textarea");
    
      if (e.which == 13) {
        if($(this).attr('data-format')){
          formatNumber($(this));
        }
        e.preventDefault();
        var nextInput = inputs.get(inputs.index(this) + 1);
        if (nextInput) {
          nextInput.focus();
        }
      }
    });