chrome_pro
chrome_pro

Reputation: 13

How to capture 'enter' key on dynamically created input tag - Vanilla JS

I have a input tag which is created dynamically. I want to listen for it's enter key keyup. I searched the internet and found only JQUERY solutions. I prefer Vanilla Javascirpt.

I have tried the following code, which seems not to work because, Ii cant select the specific element

document.addEventListener("keyup", function(event) {

    if (event.keyCode === 13) {

    }
});

Thanks, Rob Wilson

Upvotes: 1

Views: 1136

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48751

You need to do two things:

  1. Add the event listener to the container of the inputs: form, div, document, etc...
  2. Inside the listener, check for the enter key AND the expected class

const handleEnterKey = ({ key, target }) => {
  // Only if the enter key is pressed and the target is an "enter-able" input
  if (key === "Enter" && target.classList.contains('enter-able')) {
    console.log(target.value);
  }
};

// Add listener to the container that holds the inputs
const localScope = document.querySelector('.local-scope');
localScope.addEventListener('keyup', handleEnterKey);

// Added to document body after assigning the event listener
const input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', 'Dynamic...');
input.classList.add('enter-able');
localScope.append(input);
.local-scope {
  display: flex;
  flex-direction: column;
}

.enter-able {
  margin-bottom: 0.5em;
}
<div class="local-scope">
  <input type="text" class="enter-able" placeholder="Static..." />
</div>

Upvotes: 1

Tom O.
Tom O.

Reputation: 5941

See here: https://developer.mozilla.org/en-US/docs/Web/API/Document/keyup_event

const ENTER_BUTTON_KEY_CODE = 13;

document.addEventListener('keyup', event => {
  if (event.keyCode === ENTER_BUTTON_KEY_CODE) {
    console.log('Enter was pressed. Yay!');
  } else {
    console.error(`${event.code} was pressed.`);
  }
});
Press enter

Upvotes: 0

Related Questions