본문 바로가기

잡단한것들/코딩연습장

검색 자동완성 구현

    <div class="wrap" id="wrap">
    <input type="text" placeholder="search..." id="el" />
    <button type="button">submit</button>
    </div>

 

 


      input {
        border: unset;
        background-color: #e9e9e9;
        padding: 0.5em;
      }

      button {
        border: unset;
        background-color: #268ef0;
        padding: 0.5em;
        color: #fff;
        cursor: pointer;
      }

      .autocomplete-list {
        list-style: none;
        padding: unset;
        margin: unset;
        position: absolute;
        width: 100%;
      }

      .autocomplete-list li {
        border: 1px solid #e9e9e9;
      }

      .autocomplete-list li:hover {
        background-color: #f3f3f3;
      }

      .autocomplete-list button {
        border: unset;
        background-color: unset;
        display: block;
        width: 100%;
        text-align: left;
        padding: 0.5em;
      }

      .wrap {
        display: inline-block;
        position: relative;
      }

 

 

      let flag = true;

      const el = document.getElementById("el");
      el.addEventListener("input", onInputChange);
      const names = [];
      async function getData() {
        const res = await fetch("https://jsonplaceholder.typicode.com/users");
        const data = await res.json();

        names.push(...data.map(({ name }) => name));
        console.log(names);
      }

      function onInputChange() {
        if(!flag){
            return;
        }else if (flag) {
          flag = false;
          setTimeout(() => {
            console.log(el.value);
            flag = true;
          }, 300);
        }
        removeDropdown();

        const value = el.value.toLowerCase();
        if (value === "") return;
        const filteredNames = [];

        names.forEach((name) => {
          if (name.substr(0, value.length).toLowerCase() === value)
            filteredNames.push(name);
        });

        console.log(filteredNames);

        createDropDown(filteredNames);
      }

      function createDropDown(filteredNames) {
        const list = document.createElement("ul");
        list.className = "autocomplete-list";

        filteredNames.forEach((name) => {
          const listItem = document.createElement("li");
          const nameBtn = document.createElement("button");
          nameBtn.innerText = name;
          nameBtn.style.color = "#000";
          nameBtn.addEventListener("click", select);
          listItem.appendChild(nameBtn);

          list.appendChild(listItem);
        });

        document.getElementById("wrap").appendChild(list);
      }

      function removeDropdown() {
        const list = document.querySelector(".autocomplete-list");
        if (list) list.remove();
      }

      function select(e) {
        e.preventDefault();
        const btn = e.target;
        el.value = btn.innerText;
        removeDropdown();
      }

      getData();

자동완성 대충 끄적끄적 만들어봄

추후에 api 적용할 경우 너무 많은 호출이 발생하지 않도록 디바운싱 적용해둠

'잡단한것들 > 코딩연습장' 카테고리의 다른 글

랜덤 문자열 url 만들기  (0) 2023.07.16
자바로 자료구조 구현하기  (0) 2023.06.22
팝업  (0) 2022.05.23
key이벤트 테스트  (0) 2022.05.20
Vue2-datepicker 한글 커스텀하기  (0) 2021.10.25