1

Доброго времени суток!

Есть небольшая задачка:

Существует некий список контактов (по типу как в смартфоне), где изначально пользователь видит весь список, а когда вводит что-то в поиск - остаються только подходящие варианты.

В данном случае это массив из 8 объектов у которых есть атрибуты name и email.

const DATA = [
{
    name: 'Petro',
    email: "[email protected]"
}, {
    name: 'Ivan',
    email: "[email protected]"
}, {
    name: 'Igor',
    email: "[email protected]"
}, {
    name: 'Anton',
    email: "[email protected]"
}, {
    name: 'Pavlo',
    email: "[email protected]"
}, {
    name: 'Volo',
    email: "[email protected]"
},{
    name: 'Ira',
    email: "[email protected]"
}, {
    name: 'Eduard',
    email: "[email protected]"
}];

Я вывел список на экран, но при поиске у меня не возвращает результат. Не знаю что делаю не так.

Помогите разобраться, пожалуйста. Заранее спасибо=)

const DATA = [
    {
        name: 'Petro',
        email: "[email protected]"
    }, {
        name: 'Ivan',
        email: "[email protected]"
    }, {
        name: 'Igor',
        email: "[email protected]"
    }, {
        name: 'Anton',
        email: "[email protected]"
    }, {
        name: 'Pavlo',
        email: "[email protected]"
    }, {
        name: 'Volo',
        email: "[email protected]"
    },{
        name: 'Ira',
        email: "[email protected]"
    }, {
        name: 'Eduard',
        email: "[email protected]"
    }
];

let userProf = '<ul>';
for (let i = 0; i < DATA.length; i++) {
  userProf += "<li class='list'>" + "<h2>" + DATA[i].name + "</h2>" +
    "<p>" + DATA[i].email + "</p>" + "</li>";
}
document.getElementById("result").innerHTML = userProf;

document.getElementById('search').onkeyup = function() {
  document.getElementById('result').innerHTML = '';
  let stringLength = this.value.length;
  if (stringLength > 1) {
    for (let i = 0; i < DATA.length; i++) {
      let userName = DATA[i].name.split('').slice(0, stringLength).join('');
      let userEmail = DATA[i].email.split('').slice(0, stringLength).join('');
      if (userName && userEmail === this.value) {
        document.getElementById('result').innerHTML += "<li class='list'>" + "<h2>" + DATA[i].name + "</h2>" +
          "<p>" + DATA[i].email + "</p>" + "</li>";
      }
    }
  } else {
    document.getElementById("result").innerHTML = userProf;
  }
};
#result{
    width:175px;
}
input {
    margin-bottom: 20px;
}
ul {
    padding: 0;
    margin: 0;
}
.list {
    padding: 10px;
    margin-bottom: 20px;
    background: #cdcdcd;
    box-shadow:0 0 6px 0 rgba(0,0,0,0.5);
    border-radius: 6px;
}
.list:hover{
    background:#f5f5f5;
    cursor:pointer;
}
<input type='text' id='search' placeholder="friendly list" autocomplete='off'>
<div id='result'></div>

1 ответ 1

2

Не "и" &&, а "или" ||:

if (userName == searchText || userEmail == searchText) {

const DATA = [
    {
        name: 'Petro',
        email: "[email protected]"
    }, {
        name: 'Ivan',
        email: "[email protected]"
    }, {
        name: 'Igor',
        email: "[email protected]"
    }, {
        name: 'Anton',
        email: "[email protected]"
    }, {
        name: 'Pavlo',
        email: "[email protected]"
    }, {
        name: 'Volo',
        email: "[email protected]"
    },{
        name: 'Ira',
        email: "[email protected]"
    }, {
        name: 'Eduard',
        email: "[email protected]"
    }
];

let userProf = '<ul>';
for (let i = 0; i < DATA.length; i++) {
  userProf += "<li class='list'>" + "<h2>" + DATA[i].name + "</h2>" +
    "<p>" + DATA[i].email + "</p>" + "</li>";
}
document.getElementById("result").innerHTML = userProf;

document.getElementById('search').onkeyup = function() {
  document.getElementById('result').innerHTML = '';
  let searchText = this.value.toLowerCase();
  let stringLength = searchText.length;
  if (stringLength > 1) {
    for (let i = 0; i < DATA.length; i++) {
      let userName = DATA[i].name.split('').slice(0, stringLength).join('').toLowerCase();
      let userEmail = DATA[i].email.split('').slice(0, stringLength).join('').toLowerCase();
      if (userName == searchText || userEmail == searchText) {
        document.getElementById('result').innerHTML += "<li class='list'>" + "<h2>" + DATA[i].name + "</h2>" +
          "<p>" + DATA[i].email + "</p>" + "</li>";
      }
    }
  } else {
    document.getElementById("result").innerHTML = userProf;
  }
};
#result{
    width:175px;
}
input {
    margin-bottom: 20px;
}
ul {
    padding: 0;
    margin: 0;
}
.list {
    padding: 10px;
    margin-bottom: 20px;
    background: #cdcdcd;
    box-shadow:0 0 6px 0 rgba(0,0,0,0.5);
    border-radius: 6px;
}
.list:hover{
    background:#f5f5f5;
    cursor:pointer;
}
<input type='text' id='search' placeholder="friendly list" autocomplete='off'>
<div id='result'></div>

5
  • Спасибо, все заработало!) Правда я не совсем понял что делает метод toLowerCase. Если не трудно, прокомментируйте пожалуйста=) 7 фев 2020 в 14:57
  • 1
    @TarasYuro Вы уже нашли этот метод javascript-овской строки в Гугле? Что там написано?
    – user176262
    7 фев 2020 в 14:59
  • пишет, что возвращает ту же строку, только с буквами переведенными в нижний регист. Это я понял=) Я не понял почему именно этот метод) Простите, я новичок в JavaScript) 7 фев 2020 в 16:00
  • @TarasYuro Чтобы по введенному "pet" или "pET" находилось "Petro".
    – user176262
    7 фев 2020 в 16:07
  • большое СПАСИБО!) 7 фев 2020 в 16:32

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.