Paran0a
Paran0a

Reputation: 3447

Focus on field after keydown event without inserting character

I have a shortcut key K. It should focus on my input, but I don't want it to insert the letter K when it focuses.

$(document).keydown(function(event) { 
    if (event.which == 75) {
        $('input').focus();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text">

Upvotes: 5

Views: 6770

Answers (4)

arshad
arshad

Reputation: 883

This is another way:

At the time of keydown, if it is k and the input does not have focus then prevent the default behavior and give focus to the text field.

$(document).keydown(function(event) {
  if (event.which == 75 && !$('input').is(":focus")) {
    event.preventDefault();
    $('input').focus();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text">

Upvotes: 4

hudidit
hudidit

Reputation: 352

var input = $('input');

$(document).on('keyup', function (e) {
  if(input.is(':focus')){
    return;
  }
  if (e.which == 75) {
        input.focus();
    }
});
  1. Listen to the keyup event;
  2. If the input is already focused, don't focus again.

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

If you want to abruptly stop the propagation, you can also use return false;:

$(document).keydown(function(event) {
  if (event.which == 75) {
    $('input').focus();
    return false;
  }
});
$('input').keydown(function(e) {
  e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text">

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use event.preventDefault() to stop the standard behaviour of the event. Note however that this will stop the letter K from being able to be typed in the input. To allow that you need to add a keydown handler to the input itself which stops the event propagation reaching the document. Try this:

$(document).keydown(function(event) {
  if (event.which == 75) {
    event.preventDefault();
    $('input').focus();
  }
});

$('input').keydown(function(e) {
  e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text">

Upvotes: 4

Related Questions