Focus on the field after keydown event without inserting a character

I have a keyboard shortcut K. He should focus on my input, but I do not want him to insert a letter Kwhen he 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">
Run codeHide result
+4
source share
4 answers

You can use event.preventDefault()to stop the standard behavior of the event. Please note that this will result in the letter being Kunable to be entered at input. To allow you to add a handler keydownto the inputone that stops the event from propagating to document. Try the following:

$(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">
Run codeHide result
+3
source

, 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">
Hide result
+1

This is another way:

During keydown, if it is k, and the input has no focus, then prevent the default behavior and focus on 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">
Run codeHide result
+1
source
var input = $('input');

$(document).on('keyup', function (e) {
  if(input.is(':focus')){
    return;
  }
  if (e.which == 75) {
        input.focus();
    }
});
  • Listen to the event keyup;
  • If the input is already focused, do not focus again.
0
source

Source: https://habr.com/ru/post/1623913/


All Articles