Home > Enterprise >  JS/ How to search with input by firstname and lastname but also work if i type space after firstname
JS/ How to search with input by firstname and lastname but also work if i type space after firstname

Time:05-08

let input = document.getElementById('searchInput')
let searchField = document.getElementById('searchField')

input.addEventListener('keyup', (e) => {
    const string = e.target.value
const filteredUsers = users.filter((user) => {
if (string != '') {
if (user.name.first.toLowerCase().includes(string) || user.name.last.toLowerCase().includes(string)) {
 return user
 } else {
            searchField.innerHTML = ''
        }
    } else {
        searchField.innerHTML = ''
    }
})
filteredUsers.map(user => {
    personImg = user.picture.thumbnail
    person = user.name.first   ' '   user.name.last
    searchField.innerHTML  = `<li ><img src='${personImg}'>${person}</li>`

})})

I have managed to write a searching function which returns a fetched user picture, first name and last name. Searching is by first and last name. However after entering first name and if i have multiple options displayed, if i press space to enter a last name of my choice it breaks. How do i implement it to work?

CodePudding user response:

You can change || to && and it will be okay I think.

CodePudding user response:

Replace this:

const string = e.target.value
if (user.name.first.toLowerCase().includes(string) || user.name.last.toLowerCase().includes(string)) {

With this:

const q1 = e.target.value.split(' ')[0]
const q2 = e.target.value.split(' ')[1]
if (user.name.first.toLowerCase().includes(q1) && (!q2 || user.name.last.toLowerCase().includes(q2))) {}

This way, it split John Doe to John and Doe and search John in the first names and Doe in the last names.

Also If you want to type Doe and get the John Doe as result, you can use:

let foundUser = undefined;
e.target.value.split(' ').forEach(q => {
  if (user.name.first.toLowerCase().includes(q) || 
      user.name.last.toLowerCase().includes(q)) {
        foundUser = user;
  }
})
if(foundUser){...}else{...}

To search every chunk of query in first name and last name.

  • Related