hp3393
hp3393

Reputation: 13

Searching for keywords with javascript method search();

I have this program where the user can input text and then click a button to that searches for keywords in the users input if a key word is found it alert found! but if didn't work it alerts: not found! I tried something like this:

  function myFunction() {
  var str = document.getElementById('demo'); 
  var n = str.search("wow");

  if (n = true){
      alert("found");
  } else {
      alert("not found");
  }

But this didn't work. Whenever I search for something it gives me this: str.search is not a function.

Here is my full code:

function myFunction() {
  var str = document.getElementById('demo'); 
  var n = str.search("wow");

  if (n = true){
      alert("found");
  } else {
      alert("not found");
  }
  
  }
<input type="text" id="demo"/>

<button onclick="myFunction()">Search</button>

Upvotes: 0

Views: 786

Answers (2)

Unmitigated
Unmitigated

Reputation: 89234

  1. You want to check the value of the input, not the input itself.
  2. It's better to use includes here instead of search.
  3. = is assignment; == and === are for comparison. Moreover, comparing boolean values is nearly always redundant.

function myFunction() {
  var str = document.getElementById('demo').value;
  var n = str.includes("wow");
  if (n) {
    alert("found");
  } else {
    alert("not found");
  }
}
<input type="text" id="demo" />

<button onclick="myFunction()">Search</button>

Upvotes: 1

Gustavo Freire
Gustavo Freire

Reputation: 105

str in fact is not a string it's a HTML element

var str = document.getElementById('demo'); 

If you want to use str.search you have to work with regular expressions, I advise using the built in function includes for this kind of feature

Upvotes: 0

Related Questions