So I have an input field where users can enter text.
There's an 'Add' button which triggers an addVal function. In addition to triggering the addVal function when the button is pressed, I'd like the function to be triggered if the cursor is in the input field, and the enter key is pressed.
I'm able to add event listeners for either 'onfocus' or 'keypress' but not sure how to combine both conditions. Any advice on the best method or logic to achieve this with just JS/HTML?
HTML:
<label for="numAdder">Type a number here.</label>
<input type="text" id="numAdder" name="numAdder">
JavaScript:
const numField = document.getElementById('numAdder');
const addNumBtn = document.getElementById('addBtn');
addNumBtn.addEventListener('click', addVal);
function addVal(){
do stuff...
}
I've tried
numField.addEventListener('keypress', function(e){
e.preventDefault();
if(e.key==='Enter'){
addVal();
}
})
per an answer here: Trigger a button click with JavaScript on the Enter key in a text box but the input field stopped accepting text.