Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Searching for entered value using For loop (JavaScript)

I have written a code to check if a particular string that is entered through an input by a user exists within a predefined array, however I faced a problem and I am looking for help Here is the code, the problem is that the code only works for the final array 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 = "Student name found" + "\n"
    } else {
    document.getElementById("tr").innerHTML = "No match found" + "\n"
    }
    }
 })

I Have tried my best to no avail, Al Hamdulillah.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem with your code is that you are checking the input string against the entire string of all the elements in the array concatenated together. This will only match if the input string is the same as the entire concatenated string.

var QQ = "";
var arry = ["ASd", "aa", "frgr", "rgtg", "gtfh"];

document.getElementById("searchh").addEventListener("click", function() {
    QQ = document.getElementById("WW").value.toLowerCase();
    var matchFound = false; // initialize matchFound variable to false
    for (var p = 0; p < arry.length; p = p + 1) {
        document.getElementById("ggg").innerHTML = document.getElementById("ggg").innerHTML + arry[p] + " ";
        var element = arry[p].toLowerCase();
        if (QQ === element) {
            matchFound = true;
            break; // exit loop if match is found
        }
    }
    if (matchFound) {
        document.getElementById("tr").innerHTML = "Student name found\n";
    } else {
        document.getElementById("tr").innerHTML = "No match found\n";
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading