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
>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() ) )