1

What I would like to do:

  1. When the user types, show similar or matching results from array (Maximum 5 results).
  2. Each element has to be unique
  3. When the user uses 'backspace', remove also the last result(s)

When you run the code, you'll see the problem.

var allUsers = document.getElementById('searchUsers');
var value; // User input
let currentCount = 0;
let newValues = [];
var names = ["James", "Liam", "Olivia", "Mia", "Sophia", "Sophie", "Oli",
  "Olivia", "Ana", "Bianca", "James"
];

$("#searchUsers").on("keyup", function() {
  value = $(this).val();
})



$("#searchUsers").on("keyup", function() {
  let result = names.filter(item => item.toLowerCase().indexOf(value) > -1);


  // If user presses the backspace
  allUsers.addEventListener('keyup', function(event) {
    const key = event.key; // const {key} = event;
    if (key === "Backspace" && currentCount > 1) {

      //alert(key);
    }
  });



  for (let i = 0; i < result.length; i++) {

    newValues.push(result[i]);


    // If there's not input, empty the list
    if (value === '') {
      newValues = [];

    }

  }

  // Gets 5 last elements of array
  var filterResult = (newValues.slice((newValues.length - result.length), newValues.length));

  // Removes all duplicatess
  let uniqueElement = [...new Set(filterResult)];

  for (const user of uniqueElement) {
    var element = document.getElementById("searchUsers2");
    element.innerHTML += `<li><a href="/profile/${user}">${user}</a></li>`;

  }

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article class="searchArticle" style="position:absolute;z-index:1000;">
  <input id="searchUsers" type="text" placeholder="&#xF002;Search">
  <ul id="searchUsers2"></ul>

</article>

2 Answers 2

2

Maybe you don't need much scripting when using a datalist.

$(`.searchArticle`).append(
  `<datalist id="users">
   ${["James", "Liam", "Olivia", 
      "Mia", "Sophia", "Sophie", "Oli",
      "Olivia", "Ana", "Bianca"]
      .map(v => `<option value="${v}">`)
      .join(``)}</datalist>`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article class="searchArticle" style="position:absolute;z-index:1000;">
  <input type="text" id="searchUsers" 
    placeholder="&#128269; search users" list="users">
</article>

Sign up to request clarification or add additional context in comments.

1 Comment

@KoolInc Thank you for showing me a different way. Beautifully done.
1

You can try below one

  1. Create a seperate function instead of calling $("#searchUsers").on("keyup", function() each time

  2. No need for keeping extra variables like value and currentCount

  3. Keep global variables at top

const allUsers = document.getElementById('searchUsers');
    const element = document.getElementById("searchUsers2");
    
    const names = ["James", "Liam", "Olivia", "Mia", "Sophia", "Sophie", "Oli",
      "Olivia", "Ana", "Bianca", "James"
    ];

    $("#searchUsers").on("keyup", function() {
      // call this function by passing user input
      filterResults($(this).val())
    })


  function filterResults(value){
     element.innerHTML = "";
     let newValues = [];     
     const result = names.filter(item => item.toLowerCase().indexOf(value) > -1);
     
     if (value === '' || !result.length) {
          newValues = [];
      }

      for (let i = 0; i < result.length; i++) {
        newValues.push(result[i]);
      }
      
      if(value === '' || !newValues.length) {                  
          return;
       }
       
      // Gets 5 last elements of array
      var filterResult = (newValues.slice((newValues.length - result.length), newValues.length));

      // Removes all duplicatess
      let uniqueElement = [...new Set(filterResult)];
    

      for (const user of uniqueElement) {       
        element.innerHTML += `<li><a href="/profile/${user}">${user}</a></li>`;

      }
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <article class="searchArticle" style="position:absolute;z-index:1000;">
      <input id="searchUsers" type="text" placeholder="&#xF002;Search">
      <ul id="searchUsers2"></ul>

    </article>

2 Comments

Appreciate your answer! I have a question if you don't mind, when I type in, the results show (which is what I want) but when I continue typing the same results get added to the HTML. Any idea how I can fix this?
@greensky edited my answer just add element.innerHTML = ""; at begining of filterResults function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.