edit: I want to use the enter key to clear the text box after I have already typed some text. Sorry for the confusion I have caused
edit 2 The missing event parameter was the key of all this. Sorry, I am a failure as a programmer.
I want to disable the new line/break when I press enter. However, version 1 doesn't work as I won't be able to enter any text at all.
Version 2 works and I am still able to clear the field while continue entering new texts.
From how I interpret this, whether I press the shift key + enter together or not, it should still allow me to type. Why is there such a difference? How does the default option of shift key relate to enabling/disabling input on the textbox? What I would like to do, is to just disable the new line/break when pressing the enter button but I found that it disabled the input part as well, which from my understanding, it shouldn't?
// html
<textarea type="text" id="box">Some text</textarea>
// javascript
document.getElementById('box').addEventListener('keypress', (e)=>{
//version 1
if(e.keyCode == 13){ //why does this version also disable any text input?
e.preventDefault();
document.getElementById('box').value = '';
}
//version 2
if(e.keyCode == 13 && e.shiftKey){
e.preventDefault();
document.getElementById('box').value = '';
}
});
Your code is throwing an error because it doesn't know what the variable e
is referring to. You should see that error if you watch the error console. To fix it, you should pass that in to the function. This clears the textbook when you press enter. Is that what you want? I left the line in but commented it out.
document.getElementById('box').addEventListener('keypress', (e)=>{
//version 1
if(e.keyCode == 13){ //why does this version also disable any text input?
e.preventDefault();
document.getElementById('box').value = '';
}
});
<textarea type="text" id="box">Some text</textarea>