Back

Technologies:

javascriptjavascript
avatar
Tolerim
2 hours ago

How do you use a For loop in JavaScript to search for a entered value?

As a developer, I encountered an issue with my code that I wrote to find a specific string inputted by a user within a predefined array. The issue is that the code only works for the last array value. Here's the code snippet:

<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"
    }
    }
 })
Despite my attempts, I have been unable to resolve this issue. Any assistance would be appreciated. All praise is due to Allah.

Answers(1)
avatar
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.
;