0

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 code I have, basically it determines whether or not the word "bob" has been entered in the textarea.

<script>

function findBob() {
    var inputText = document.getElementById("box").innerHTML;
    if(inputText === "bob") {
        document.getElementById("box").innerHTML = "true";
    } 
    if (inputText !== "bob") {
        document.getElementById("box").innerHTML = "false";
    }
}
</script>

<textarea rows=10; col= 5; id="box">
bob</textarea>

<button onClick="findBob();">FIND BOB</button>

Now, after I click the button saying "FIND BOB", it changes the text to "true" which is perfect, however, if I add some gibberish to the textarea, then click FIND BOB again, nothing happens. If I do anything to the textarea the function will not work. Even if I reload the page, backspace "bob" and retype "bob" nothing happens.

Now I expect that I have broken some JavaScript syntax, or some such thing, but I cannot figure it out. What am I doing wrong?

-EDIT- I am using ===, as opposed to other methods because of this other StackOverflow post, find it here.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
JeremiahDuane
  • 374
  • 4
  • 15

2 Answers2

-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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

@Quentin answered your basic question, but you can refactor your code to the following to be better:

function findBob() {
  // keep a reference to the textarea DOM element instead of looking up multiple times
  const 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 contents
  if (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;
  }
}
Geuis
  • 41,122
  • 56
  • 157
  • 219
  • Thanks! That helps too. That was my next step in the project. I've exclusively done java in the past, so js is new to me. – JeremiahDuane Aug 05 '18 at 22:14