What is the difference between . on('input') / . on('Paste') / . on('change')?

Asked

Viewed 1,147 times

2

I was trying to do a validation but with the .on('input') it works better than the .on('Paste') (I needed to put a timeout to make it work), can anyone explain to me the difference between the two? Follow my code to illustrate the question:

Paste

$(this).on("paste", "#email", function(event) {
        var $obj = $(this);
            setTimeout(function() {
                var str  = $obj.val();
                $obj.val(str.replace(/[^a-za-uA-ZA-U0-9_@\.\'\b\t]/g, ''));
            }, 2);
        });

input

$(this).on("input", "#email", function(event) {
        var $obj = $(this);
                var str  = $obj.val();
                $obj.val(str.replace(/[^a-za-uA-ZA-U0-9_@\.\'\b\t]/g, ''));
        });

change

 $(this).on("change", "#email", function(event) {
            var $obj = $(this);
                    var str  = $obj.val();
                    $obj.val(str.replace(/[^a-za-uA-ZA-U0-9_@\.\'\b\t]/g, ''));
            });

3 answers

5


The event input is more generic and fires for example with paste or keyboard events. The paste is more specific and does not fire when writing with the keyboard.

The paste will fire first and then the input.

Another generic event is the change, which works like input basically but doesn’t fire right away. Sometimes only when input loses focus.

You can test here:

$('input').on('change paste keyup input', function(e) {
  console.log(e.type, this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

  • Who gave the -1 I invite you to motivate to realize what may be wrong in my reply.

1

So the difference is simple on-input is called only when you introduce some value, and the on-paste will only be calling the necklaces a value Ctrl + v

Take a look at this basic example:

$('input').on('change', function() {
  console.log('change ' + this.value);
});

$('input').on('input', function() {
  console.log('input ' + this.value);
});

$('input').on('paste', function() {
  console.log('paste ' + this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

0

The basic difference is that the oninput is fired whenever the user enters any value in the field, while the onpaste is only when the user "glue" some information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.