Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
Prevent default on select focused

I am trying to prevent default on press F1 so it doesn't open a new tab to support.google.com, instead I want to use it as a hotkey for my app, this is working everywhere, except when I focus a select element for some reason. I put an example:

<!DOCTYPE html>
<html lang="en">

<body>
    <input type="text">

    <select onkeydown="" name="" id="">
        <option value="a">a</option>
    </select>
</body>

</html>

<script>
    window.addEventListener('keydown', (e) => {
        e.preventDefault()
    })
    document.getElementsByTagName('select')[0].addEventListener('keydown', (e) => {
        e.preventDefault()
    })
    document.getElementsByTagName('option')[0].addEventListener('keydown', (e) => {
        e.preventDefault()
    })
</script>

Here if you press F1, it wont do anything, if you focus on the input and press F1 won't do anythin also, but if you open the select dropdown and press F1 then is going to open the help tab. Thats the problem. Any idea how to fix this?

EDIT: So it seems to be a windows/chrome bug, in mozilla this same code works as expected. The prevent event in select and option are not necesary but I put them just in case.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You have to attach the event handler on the document rather than window or a particular element:

document.addEventListener("keydown", function(e) {
  if (e.key === "F1") {
    e.preventDefault();
    console.log("F1 Pressed!");
  };
}, false);
<select name="" id="">
  <option value="a">a</option>
</select>

Also your code overrides the onkeydown on the <select> tag. Kindly remove that too.

In the above preview, irrespective of your focus is on the <select> tag or not, F1 is being controlled by JavaScript.

Preview here:

preview

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!