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

How to show relevant results when searching

I have a project that contains an input and an array. When I search inside the input for something, I want it to show me the relevant results in the array based on the common characters

This is my code:

<input type="text" />
<div></div> 
$(document).on("keyup keypress","input",function()
{
  let input = $(this)
  
  let array = ["tide","taet","oks","mos"]  
  
  storage = ""
  
  for( let x = 0; x < array.length; x++ )
    { 
      if( input.val() === array[x] )
        {
          storage = array[x] // I will use the stored text later
          
           $("div").append(`<p>this is : ${array[x]}</p>`)
          
          return
        }
      
        if( input.val() !== array[x] )
        {
           $("div").empty()
        }
    }
});

By the way, the code works, but it does not show me the results until I type the entire word

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 :

This is because your if condition is trying to match the input to the whole array string. So it will only work once the entire string value from the array is typed.

if( input.val() === array[x] )

Try instead to check if the string from the input is contained within the array value.

if( array[x].includes( input.val() ) )
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