Technologies:
Tolerim
2 hours ago
How do you use a For loop in JavaScript to search for a entered value?
<p id="ggg"></p>
<p id="tr"></p>
<input type="text" id="WW" value="">
<button type="submit" id="searchh">Search for name</button>
var QQ=""
var arry= ["ASd", "aa", "frgr", "rgtg", "gtfh"]
<script>
document.getElementById("searchh").addEventListener("click", function() {
QQ = document.getElementById("WW").value.toLowerCase()
for (var p=0; p<arry.length;p=p+1) {
document.getElementById("ggg").innerHTML = document.getElementById("ggg").innerHTML+
arry[p] + " "
var OO= document.getElementById("ggg").innerHTML.toLowerCase()
if (QQ==OO) {
document.getElementById("tr").innerHTML = "The student's name was found." + "\n"
} else {
document.getElementById("tr").innerHTML = "No match found." + "\n"
}
}
})
Answers(1)
Tolerim
2 hours ago
Verified Answer
The issue with your code is that you are checking if the entire contents of the ggg element match the input string, instead of checking if the input string matches the current element in the array. Additionally, you are overwriting the "No match found" message on each iteration of the loop, so you only see the result for the last element in the array.
Here is an updated version of your code that should work:
<p id="ggg"></p>
<p id="tr"></p>
<input type="text" id="WW" value="">
<button type="submit" id="searchh">Search for name</button>
<script>
var arry = ["ASd", "aa", "frgr", "rgtg", "gtfh"];
document.getElementById("searchh").addEventListener("click", function() {
var inputString = document.getElementById("WW").value.toLowerCase();
var matchFound = false;
for (var i = 0; i < arry.length; i++) {
var currentString = arry[i].toLowerCase();
document.getElementById("ggg").innerHTML += arry[i] + " ";
if (currentString === inputString) {
matchFound = true;
}
}
if (matchFound) {
document.getElementById("tr").innerHTML = "Student name found";
} else {
document.getElementById("tr").innerHTML = "No match found";
}
});
</script>
In this updated version, we are iterating over the array and comparing each element individually to the input string. We are also only updating the "No match found" message once at the end of the loop, based on whether we have found a match or not.