JavaScript 자동 완성/제안 기능을 구현하기 위한 코드는 다음과 같습니다. -
예시
<!DOCTYPE html> <html> <head> <style> body{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } </style> </head> <body> <h1>JavaScript Auto Complete / Suggestion feature</h1> <input type="text" list="datalist" class="fruits" /> <datalist id="datalist"> <option value="orange"></option> <option value="apple"></option> <option value="pineapple"></option> <option value="guava"></option> <option value="mango"></option> <option value="peach"></option> <option value="pomegranate"></option> <option value="litchi"></option> </datalist> <script type="text/javascript"> var tags = ["orange", "apple","pineapple","guava","mango","pomegranate","litchi",]; let check; document.querySelector(".fruits").addEventListener("keyup", (event) => { let value = event.target.value; document.getElementById("datalist").innerHTML = ""; tags.forEach((item) => { if (item.toLowerCase().indexOf(value.toLowerCase()) > -1) { var opt = document.createElement("option"); var sel = document.createTextNode(item); opt.appendChild(sel); document.getElementById("datalist").appendChild(opt); } }); }); </script> </body> </html>
출력
입력 필드에 무언가를 입력할 때 -