How Can I Read The Text In A Textarea With Javascript?
So I am new to JS and am trying to figure out the basics. I decided to make a basic web page text editor. Right now I am trying to differentiate between words with JS. Here is the
Solution 1:
The innerHTML
of a textarea represents its default value.
Changing the default value with JavaScript only has an effect if either:
- The value has not been changed from the default value or
- The form is reset
After you type in the textarea, neither of these is true.
Use the value
property to alter the current value and not the innerHTML
.
Solution 2:
@Quentin answered your basic question, but you can refactor your code to the following to be better:
functionfindBob() {
// keep a reference to the textarea DOM element instead of looking up multiple timesconst textarea = document.getElementById('box');
// if statements have an else component, so you only need to check once for the truthy condition.// access the content of the textarea via `value`. `toLowerCase` ensures that Bob, bob, BOB, etc all match true// `indexOf` checks if the 'bob' value is found anywhere in the contentsif (textarea.value.toLowerCase().indexOf('bob') > -1) {
// use the reference to the textarea here.// Don't need to use true/false as strings, you can set them directly.
textarea.innerHTML = true;
} else {
textarea.innerHTML = false;
}
}
Post a Comment for "How Can I Read The Text In A Textarea With Javascript?"