[JavaScript / jQuery] 검색어 자동완성 기능

728x90
<style>

/* 현재 선택 된 검색어 */
.autocomplete > div.active {
  background: #e0e5f6;
  color: #000;
}

.autocomplete > div {
  background: #f1f3f499;
  padding: .2rem .6rem;
}

section {
  width: 500px;
  padding: 1.5rem 1.6rem;
  box-shadow: 0 0 1rem rgba(0, 0, 0, .05);  
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background: #fff;
  margin-top: 2rem;
}

</style>

 

 

        <div class="d-flex flex-column bd-highlight mb-3 search-container">
            <div class="p-2 bd-highlight srarch-content">
            	<input type='number' placeholder="차량번호를 입력해주세요." class="search-box" id="search" autocomplete="off">
            </div>
            <div>
            	<div class="autocomplete"></div>
            </div>
        </div>

 

	//검색어 자동완성 
	const $search = document.querySelector("#search");
	const $autoComplete = document.querySelector(".autocomplete");
	
	let nowIndex = 0;
	
	$search.onkeyup = (event) => {
	  // 검색어
	  const value = $search.value.trim();
	
	  // 자동완성 필터링
	  const matchDataList = value
	    ? carNumList.filter((label) => label.includes(value))
	    : [];
	
	  switch (event.keyCode) {
	    // UP KEY
	    case 38:
	      nowIndex = Math.max(nowIndex - 1, 0);
	      break;
	
	    // DOWN KEY
	    case 40:
	      nowIndex = Math.min(nowIndex + 1, matchDataList.length - 1);
	      break;
	
	    // ENTER KEY
	    case 13:
	      document.querySelector("#search").value = matchDataList[nowIndex] || "";
	
	      // 초기화
	      nowIndex = 0;
	      matchDataList.length = 0;
	      break;
	      
	    // 그외 다시 초기화
	    default:
	      nowIndex = 0;
	      break;
	  }
	
	  // 리스트 보여주기
	  showList(matchDataList, value, nowIndex);
	};
	
	const showList = (data, value, nowIndex) => {
	  // 정규식으로 변환
	  const regex = new RegExp(`(${value})`, "g");
	  
	  $autoComplete.innerHTML = data
	    .map(
	      (label, index) => `
	      <div class='${nowIndex === index ? "active" : ""}'>
	        ${label.replace(regex, "<mark>$1</mark>")}
	      </div>
	    `
	    )
	    .join("");
	};
728x90