0

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

  • Does this answer your question? [What is DOM Event delegation?](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) – Alon Eitan May 07 '21 at 14:29

2 Answers2

0

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 VK_ENTER = 13;

const handleEnterKey = ({ keyCode, target }) => {
  // Only if the enter key is pressed and the target is an "enter-able" input
  if (keyCode === VK_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>
Mr. Polywhirl
  • 31,606
  • 11
  • 65
  • 114
0

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
Tom O.
  • 5,133
  • 2
  • 19
  • 33