Checking if value exists in an array via search field

2

In pure javascript I can use indexOf() , something like this:

var chaves = ['wmv','3gp','mp4','mp3','avi'];
if(chaves.indexOf("avi") != -1)
{  
    alert("Ok!");
} 

But when it comes to a search field I'm trying this way:

<html>
   <body>
       <input type="text" id="txt" onblur="verifica()"/>
   </body>
   <script>
       var chaves = ['wmv','3gp','mp4','mp3','avi'];
       var item = document.getElementById('txt').value;
       function verifica()  {
            for(var i = 0; i < chaves.length; i++) 
            {
               if(chaves[i].length == item)     {
                   alert("SIM")
               } else {
                   alert("NAO")
               }
            }
       }
   </script>
</html>

The worst is that I've done it once and now I do not remember it anymore .. if anyone can help.

    
asked by anonymous 26.12.2016 / 20:29

2 answers

5

If you can use your first example, you should only change its verifica() function:

function verifica() {
  var chaves = ['wmv', '3gp', 'mp4', 'mp3', 'avi'];
  var item = document.getElementById('txt').value;
  if (chaves.indexOf(item) > -1) {
    alert("Encontrou");
  } else {
    alert("Não encontrou");
  }
}
<input type="text" id="txt" onblur="verifica()" />

Reference JavaScript String indexOf () Method

    
26.12.2016 / 20:33
2

Today there is a more current and functional alternative to finding out if a given value belongs to an array. You can use the Array.prototype.includes() of ES7 method.

Rewriting the answer, we would have the following code:

const verifica = (item) => {
   const chaves = ['wmv', '3gp', 'mp4', 'mp3', 'avi'];
   chaves.includes(item) ? alert("Encontrou") : alert("Não encontrou");
}

Using as follows:

verifica(document.getElementById('txt').value);

However method, includes() is not supported in older browsers, this can be a problem if you do not use some transpiler to convert from ES7 to ES5.

Below is the list of supported browsers:

Compatibility ( can I use ) Array.prototype.indexOf :

Compatibility( can I use ) Array.prototype.includes :

Reference: link

    
31.01.2018 / 16:17