0

I have a search box which is by default not autofocused. So i am putting a keypress event on the body i.e. when forward slash (/) is pressed the search box should be in focus. Although on key press it puts the search box in focus but also puts the "/" in the search box.

body.onkeypress = (e) => {
    if(e.which === 47) {
        searchInput.focus()
    }
} 

How should I fix this?

ankitjt
  • 477
  • 1
  • 5
  • 15
  • 1
    Not quite sure, but I think you have to change the default behavior of the `keyPress` to avoid this. You could try to do : `e.prevenDefault()` in your function and return `false` at the end so that the real behavior is not triggered https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault – Gregoire Ducharme Jul 01 '22 at 06:56
  • You can clear the input field after focusing – Maddy8381 Jul 01 '22 at 07:00
  • Thanks for this it is working now, but it now refrains from registering any other key stroke as in the search box is in focus but I cannot type anything in it. – ankitjt Jul 01 '22 at 07:04
  • you'll need to show more code for context – Bravo Jul 01 '22 at 07:04
  • `event.which` is deprecated. see: [Alternative for event's deprecated KeyboardEvent.which property](https://stackoverflow.com/questions/49278648/alternative-for-events-deprecated-keyboardevent-which-property) – pilchard Jul 01 '22 at 07:07

2 Answers2

3

Use preventdefault to prevent the '/' from being typed.

Make sure you do this in your if statement, otherwise all characters get blocked.

body.onkeypress = (e) => {
    if(e.which === 47) {
        e.preventDefault()
        searchInput.focus()
    }
} 

https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

Wimanicesir
  • 4,606
  • 2
  • 11
  • 30
0
  <body id="body">
  <input type="text" id="elementid" />
</body>
<script>
  document.onkeypress = (e) => {
    if (e.which === 47) {
      document.getElementById("elementid").focus();
      setTimeout(() => {
        str = document.getElementById("elementid").value = document
          .getElementById("elementid")
          .value.slice(0, -1);
      });
    }
  };
</script>