typeahead.js #
- typeahead는 검색기능을 제공하는 자바스크립트 라이브러리다. 다른 라이브러리에서 제공해주는 Select2 jQuery 기반의 플러그인도 있지만 typeahead를 더 편리하게 사용할 것 같다.
typeahead 사용법 #
- typeahead를 사용하기 위해서는 typeahead.bundle.js를 추가 해줘야 한다.
-
jQuery 기반 라이브러리이기 때문에 jQuery는 필수로 추가 해줘야 한다.
<script src="/resources/js/jquery-3.6.0.min.js'"></script> <script src="/resources/js/typeahead.bundle.js"></script>
-
만약 스크립트를 추가했는데도 스크립트를 찾지 못하거나 안된다면 jQuery의 버전을 확인해 보도록 한다. 버전이 너무 높거나 낮으면 적용되지 않을 수도 있다.
-
style css는 추가해도 되고 기본을 사용해도 된다.
<style> .typeahead-div { width: 400px; } .tt-menu { width: 100%; } .typeahead, .tt-query, .tt-hint { height: 30px; padding: 8px 10px; font-size: 24px; line-height: 30px; border: 2px solid #ccc; -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px; outline: none; } .typeahead { background-color: #fff; } .typeahead:focus { border: 2px solid #0097cf; } .tt-query { -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .tt-hint { color: #999 } .tt-dropdown-menu { margin-top: 3px; padding: 8px 0; background-color: #fff; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.2); -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2); -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, .2); box-shadow: 0 5px 10px rgba(0, 0, 0, .2); } .tt-suggestion { width: calc(100% -20px); padding: 3px 10px; font-size: 18px; line-height: 24px; color: black; cursor: pointer; } .tt-suggestion.tt-cursor { color: #fff; background-color: #cccccc; } .tt-suggestion p { margin: 0; font-size: 18px; text-align: left; } </style>
-
기본형태
- style 적용
-
jsp화면구성
<div> <h1>typeahead</h1> <div id="the-basics"> <input class="typeahead" type="text"> </div> </div>
-
javascript부분
<script> let states = [ '대한민국', '미국', '일본', '중국', '캐나다', '스페 인', '독일', '영국' ]; let substringMatcher = function(strs) { return function findMatches(searchWord, cb) { let matches, substringRegex; // 추천 목록으로 보일 배열 matches = []; // searchWord로 만들어질 정규 표현식 substrRegex = new RegExp(searchWord, 'i'); //정규 표현식으로 가지고 있는 배열에서 탐색 $.each(strs, function(i, str) { if (substrRegex.test(str)) { //정규 표현식 일치하면 추천 목록에 푸시 matches.push(str); } }); cb(matches);//뿌려주는 함수 }; }; $('.typeahead').typeahead( { hint: true, // 나머지 글자가 자동으로 보여지는지 highlight: true,// 일치하는 문자 하이라이팅 minLength: 1, // 검색 시작하는 최소 문자 길이 }, { limit: 5, // 자동완성 목록에 보여질 개수 name: 'states', //source가 검색어 추천에 목록으로 뿌려질 목록이다. source: substringMatcher(states), templates: { //추천 목록 헤더 header: '<h3 class="league-name">나라</h3>', empty: [ '<div class="empty-message">', '일치하는 결과가 없습니다', '</div>' ].join('\n') // 일치하는 결과가 없을 때 } } ) </script>
-
결과
참고 사이트 #
- typeahead.js examples(https://twitter.github.io/typeahead.js/examples/)
- typeahead.js doc(https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md)