Home > Software design >  JavaScript Array to HTML - function to show specific elements
JavaScript Array to HTML - function to show specific elements

Time:08-12

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  style="position:absolute;z-index:1000;">
  <input id="searchUsers" type="text" placeholder="&#xF002;Search">
  <ul id="searchUsers2"></ul>

</article>

CodePudding user response:

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  style="position:absolute;z-index:1000;">
  <input type="text" id="searchUsers" 
    placeholder="searchUsers" list="users">
</article>

CodePudding user response:

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){    
     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) {
          element.innerHTML = "";        
          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  style="position:absolute;z-index:1000;">
      <input id="searchUsers" type="text" placeholder="&#xF002;Search">
      <ul id="searchUsers2"></ul>

    </article>

  • Related