I am relatively new to javascript and am trying to get the last line of text in a a textarea on a key press. Is this possible? My code is below.
const textarea = document.getElementById('textarea');
textarea.addEventListener("keydown", (event) => {
if (event.code != 13) {
return "Enter key was not pressed"
}
else if(event.code === 13) {
//Do what my question is asking
}
});
I have tried to get the innerHTML property and the value property of the textarea but that returned the full contents of the textarea, not the last line which is what I need.
const textarea = document.getElementById('textarea');
//First thing I tried
let content = textarea.innerHTML;
console.log(content);
//Second thing I tried
let content2 = textarea.value;
console.log(content2);
CodePudding user response:
Yes, this is very much possible.
textarea.addEventListener("keydown", (event) => {
if (event.code != 13) {
return "Enter key was not pressed"
}
else if(event.code === 13) {
textarea.substr(textarea.lastIndexOf("\n") 1);
}
});
This is accomplished using the .substr()
method of JavaScript
.
CodePudding user response:
First off I'll point one error in your code so it can work properly:
You are comparing event.code != 13
. event.code
is a string that identifies the key; you are using it like event.keyCode
which is a number. So for your code to work you need to either use event.keyCode != 13
or event.code != "Enter"
(I recommend the last one)
Second you can get the last line of the text area by first accesing its .value, then getting a substring from the lastIndex of "\n" which represents a line break. (This part is the same as @Anye answer; It works in concept but there is an implementation error, thats why I write this answer)
Last some improvements to make the code better:
- dont use type less comparison !=, use strict comparison !== to make your code safer
- because in your if you are returning, then there is no need for else statement. Thats because if the key is different from enter, then it will return, thus if it gets past the if, the only code possible is enter; no need to compare again
- returning a string from an event wont do anything; its better to leave it as a comment for semantic reasons
This is a working example
const myTextArea = document.getElementById("myTextArea");
myTextArea.addEventListener("keydown", (event) => {
if (event.code !== "Enter") {
return; // Enter key was not pressed
}
// Enter was pressed, the last line will be outputed to the console
console.log(myTextArea.value.substr(myTextArea.value.lastIndexOf("\n") 1));
});
<textarea id="myTextArea"></textarea>