Stop multiple Jquery events

0

I have the following situation:

$('input[name=buscar]').on( "keydown keypress keyup", function( event ) {
    console.log('foi');
});

Every time I type, all 3 events are triggered. How do I get only 1 to be fired, instead of the 3? that is, I clicked on the button, fired the first event, instead what it should do and ready ...

    
asked by anonymous 08.04.2016 / 14:54

3 answers

2

I think it's running because it's three different events but they would run at the same time. I'll explain:

keyup () : The event occurs when the key returns to its original position on the keyboard (example: when you release the key).

keydown () : The event occurs when the key is pressed.

keypress () : The event occurs when the key is pressed.

The difference between keydown () and keypress () is that the second one is not captured when the ctrl, alt, or shift keys are pressed.

So, if you press a key, you will go through the 3 "states" shown above, to trigger only one, you could use only one of the functions and remove the others.

    
08.04.2016 / 15:09
1

You can pick up the event type and put in a condition to separate where each event:

$('input[name=buscar]').on("keydown keypress keyup", function(event) {
  if (event.type === 'keydown') {
    console.log('1');
  } else if (event.type === 'keypress') {
    console.log('2');
  } else if (event.type === 'keyup') {
    console.log('3');
  }
});

Or chaining multiple events.

$('input[name=buscar]').on("keydown", function() {
  console.log('1');
}).on('keypress', function() {
  console.log('2');
}).on('keyup', function() {
  console.log('3');
});
    
08.04.2016 / 15:03
1

Since you are using these events in an input, I believe the following code is the simplest way to solve your problem:

$('input[name=buscar]').change( function() {
  console.log('foi');
});
    
08.04.2016 / 15:42