Reputation: 13
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
Reputation: 89234
value
of the input, not the input itself.includes
here instead of search
.=
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
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