Reputation: 13
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
Reputation: 48751
You need to do two things:
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
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