Myterion
Myterion

Reputation: 3

How to add an 'Enter' key event listener to an input bar that I've grabbed with querySelector?

Basically, I'm following this exercise https://www.youtube.com/watch?v=EerdGm-ehJQ&t=50183s 14n, part 2.

My page looks like this:I'm focusing on the input bar with the '3' inside it

When I press 'Enter' I want to run some code (the console.log is just a test), but I can't even get Javascript to recognise the 'event.key' part that I'm using to select 'Enter'

Here's what I have, and 'event' is crossed out and is 'deprecated' (idk what that means)

document.querySelectorAll('.quantity-input')
  .forEach((inputBar) => {
    inputBar.addEventListener('keydown', () => {
      if (event.key === enter) {
        console.log('hello')
      }
    })
  }) 

The '.quantity-input' is the class name of the input bar where you type the quantity.

To me, the code above does this:

  1. Get every input element on the page
  2. For each of those input elements, make them look out for key presses on the keyboard.
  3. If one of those keypresses is equal to 'Enter'.
  4. Run some code

But the 'event' in 'event.key' is crossed out.

I'm sorry I couldn't word this question any better, the project is quite big and it's hard to know what relevant bits of code to include.

Btw, when I click enter, this is what the page will look like (the exact same as when I click save) The update button comes back, ready to be pressed again

edit: just including an example of the deprecated 'event'deprecated event

Thanks for the help, this has now been solved. truly thank u

Upvotes: 0

Views: 121

Answers (1)

Ahineia
Ahineia

Reputation: 46

You need to pass your event to inner function to recognise it.

Also wrap "Enter" to tell code it is a string to compare with.

Like that:

document.querySelectorAll('.quantity-input')
  .forEach((inputBar) => {
    inputBar.addEventListener('keypress', (event) => {
      if (event.key === "Enter") {
        const element = event.target;
        element.value = "Pressed!";
      }
    });
  })
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <link rel="icon" href="/favicon.ico">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>tmp</title>
</head>

<body>
  <div id="app">
    <input class="quantity-input" type="text" value="some" />
  </div>
</body>

</html>

Upvotes: 0

Related Questions