pers0n
pers0n

Reputation: 155

How to prevent F5 from being typed into html input on page reload

I'm making a calculator app, I added an event listener to the document to listen to number keypresses, like so:

    function listenForKeyPress() {
       // add document event listener for all key presses
       document.addEventListener('keyup', (e) => {
          // check to see if the keypress was a number
          if (/[0-9-+-\--.]/g.test(e.key)) {
             // check to see if the input is not already focused
             if (document.activeElement !== input) {
                // focus element
                input.focus();
                // focus value
                input.value += e.key;
             }
          }
      })
    }

    // call function
    listenForKeyPress();

The problem is when I refresh the page using F5 I get F5 typed into the input element, like so: enter image description here

How can I prevent this from happening, thanks in advance.

Upvotes: 1

Views: 240

Answers (2)

Akxe
Akxe

Reputation: 11485

I usually use isNaN(+variable) as a check for a number in string. Regexp is way too expensive for a task this simple.

['-5', '5', 'F5', ' 5'].forEach(value => {
  const valueAsNumber = +value;
  console.log(`"${value}" is ${isNaN(valueAsNumber) ? 'not' : ''} a number. (${valueAsNumber})`); 
})

Upvotes: 0

Jeremy Thille
Jeremy Thille

Reputation: 26360

I think you can modify your regex like this :

  1. Match only one character by starting with ^, ending with $ and removing the global /g flag
  2. [0-9-+-\--.] is weird, as it matches - twice, and also the range "+" to "-" (char code 43 to 45). I think you want to prefer [\d-+*\/.] to match either a digit (\d), one of the operators +-*/ or the dot.

Which gives :

const regex = /^[\d-+*\/.]$/;

regex.test("F5"); // false
regex.test("a"); // false
regex.test("5"); // true
regex.test("+"); // true

Upvotes: 2

Related Questions