Checking if value exists in an array via search field

Asked

Viewed 38,101 times

7

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

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

But in the case of a search ground 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 thing is I’ve done it once and now I can’t remember anymore. if anyone can help me.

2 answers

8


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

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

where the return goes > -1 found the index you are searching for if it is -1 was not found.

6

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

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 the method, includes() is not supported in older browsers, this may be a problem if you do not use some transpilator to make the conversion from ES7 to ES5.

Below is the list of supported browsers:

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

inserir a descrição da imagem aqui

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

inserir a descrição da imagem aqui

Reference: https://www.w3schools.com/jsref/jsref_includes.asp

Browser other questions tagged

You are not signed in. Login or sign up in order to post.