Nick van der Waal
Nick van der Waal

Reputation: 414

make on keyup only fire once inside of an input

I have this method:

jQuery(function($) {
    var input = $('#search');
    input.on('keyup', function() {
        var key = event.keyCode || event.charCode;
        if( key == 8 || key == 46 ) {
            console.log('ajax request cancelled');
            recentRequest.abort();
        }
    });
});

but as of right now everytime I press Backspace it will fire, I want to make it so it can only be fired once inside of my input. Anyone have an idea?

Thanks

Upvotes: 3

Views: 370

Answers (1)

Milan Chheda
Milan Chheda

Reputation: 8249

You can create a backspaceFlag variable to ensure that backspace code is allowed/triggered only once:

jQuery(function($) {
  var backspaceFlag = true;
  var input = $('#search');
  input.on('keyup', function() {
    var key = event.keyCode || event.charCode;
    if ((key == 8 || key == 46) && backspaceFlag) {
      backspaceFlag = false;
      console.log('ajax request cancelled');
      recentRequest.abort();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='search' />

Upvotes: 2

Related Questions