Adam Adam - 12 days ago 5
HTML Question

Compare input to array

I have a list that I want to compare to a input value and when the input value doesn't match anything in my list I want to make an alert(Album don't exist).

Here my search bar:-

<input id="search" type="text" name="text" placeholder="Album name">
<button onclick="sendToPage()">Search</button>`


And here my list:-

var validSearch = ["The Stage", "Hail to the King", "Nightmare", "Avenged Sevenfold", "City of Evil", "Waking the Fallen", "Sounding the Seventh Trumpet"];


I have read a suggestion but can´t get my head around it.. :)

Answer

You can use indexOf on arrays. It returns the index of the element matched. Only thing I'd suggest is you turn the search array lower or upper case first, so matching doesn't rely on the person typing it EXACTLY as you have defined it with every capital letter exactly as you wrote it.

function match(elem) {
   var validSearch = ["The Stage", "Hail to the King", "Nightmare", "Avenged Sevenfold", "City of Evil", "Waking the Fallen", "Sounding the Seventh Trumpet"];
   var index = validSearch.indexOf(elem.value);
   if(index == -1) {
      window.alert("Album does not exist. Please try again");
   }
   else {
      var album = validSearch(index);
   }
}


<input id="search" type="text" name="text" placeholder="Album name">
<button onclick="match(document.getElementById('search'))">Search</button>`

    function match(elem) {
       var validSearch = [
                        "The Stage", 
                        "Hail to the King", 
                        "Nightmare", 
                        "Avenged Sevenfold", 
                        "City of Evil", 
                        "Waking the Fallen", 
                        "Sounding the Seventh Trumpet"];
      
      /** make search case insentive **/
      var searchKeys = [];
       for(c=0;c<validSearch.length;c++) {
           searchKeys[c] = validSearch[c].toLowerCase();
       }
       /** search the input **/
       var index = searchKeys.indexOf(elem.value.toLowerCase());
        
       /** if not matched **/
       if(index == -1) {
          window.alert("Album does not exist. Please try again");
       }
       else {
          var album = validSearch[index];
          window.alert("FOUND IT! " + album);
       }
    }


    
<input id="search" type="text" name="text" placeholder="Album name">
<button onclick="match(document.getElementById('search'))">Search</button>

Comments