-1

I have an issue which is that I have a class that validates an input to only allow numbers:

$(function() {
    $( '.validate_numbers' ).bind('keypress', function (e) {
        //console.log(e.which);
        return (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) ? false : true;
    });
});

But when I append another input:

$('#persons').append('<input type="text" class="validate_numbers">');

with the same class it doesn't validate the input and allows any character you type.

How can I invoke jquery to apply the keybind to the inputs that I append?

Jose
  • 45
  • 1
  • 8

1 Answers1

2

Use event delegation.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$( '#persons' ).on('keypress','.validate_numbers', function (e) {
    //console.log(e.which);
    return (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) ? false : true;
});

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125