잡담소장소

[javascript] jquery-typeahead 적용기 본문

Study ;3

[javascript] jquery-typeahead 적용기

유부뽀 2020. 12. 2. 10:50

프로젝트 진행 중에 제공해야 할 검색기능이 있어서 autocomplete같은 플러그인을 찾아봤는데

대부분 태그 형식의 UI라서 내가 하고자하는 기능 구현을 위해 좀더 검색하다가 발견하게된 jquery-typeahead

 

jQuery Typeahead | jQuery Plugin Registry

jQuery Typeahead by Tom Bertrand jQuery plugin that provides Typeahead (autocomplete) Search preview from Json object(s) via same domain Ajax request or cross domain Jsonp and offers data compression inside Local Storage. The plugin is built with a lot of

plugins.jquery.com

 

www.runningcoder.org/jquerytypeahead/demo/

 

jQuery Typeahead Search Demo

Try jQuery Typeahead Search plugin demos, see how the options can be user to customize your search bar.

www.runningcoder.org

 

열심히 고민하면서 적용한 결과물

$.typeahead({
	maxItem: 100, //default 8, 노출하고자 하는 개수 변경
	backdropOnFocus: true, //검색 후 focus out으로 사라진 list를 focus in으로 다시 노출
	input: "#selector", // query selector
	dynamic: true, //결과를 매번 호출 ajax call할때 사용
	delay: 500, //dynamic true일 경우, api 호출 delay
	emptyTemplate: "결과가 없습니다. 다시 검색해주세요.",
	minLength: 1, //최소 검색어 길이
	order: "asc",
	//highlight: true,  //template에서 처리, highlight의 경우 display에 설정된값만 처리됨
	template: function( query, item ){ //검색어에 highlight
		let result = item.result.replace(
			new RegExp(query, 'gi'),
			function(query, target){ return '<strong>'+query+'</strong>'; }
		);
		return '<span class="typeahead__display">'+result+'</span>';
	},
	source:{
		search:{  //임의의 group name
			display: "result", //검색 결과에서 노출하고 싶은 값, 배열 가능
			ajax: function(query){ //selector 에서query 가져옴
				return {
					type: "POST",
					url: "/api/search",
					path: "data.itemsPerPage", //결과값에서 가져올 목록 위치
					data: { query: '{{query}}' },
					callback: {
						done: function( resp ){
							return resp;
						},
					}
				}
			}
		}
	},
	callback: {
		onNavigateBefore: function(node, query, event) {
			if (~[38,40].indexOf(event.keyCode)) { //커서 이동 시 검색어가 변경되지 않도록
				event.preventInputChange = true;
				return false;
			}
		},
		onClickAfter: function(node, a, item, event){ // 조회 목록을 클릭 했을 때
			searchSelector.chosenNo = item.no;
			$("#selector").attr('disabled', true);
		},
		onCancel: function(node, event){ //취소 버튼 클릭 or 텍스트가 전부 지워질경우
			$("#selector").attr('disabled', false);
			$("#selector").focus();
		},
	}
});

 

공식홈에 올라와있는 플러그인이라 그런지 가이드나 구성자체가 꼼꼼하게 잘되어 있다는 느낌 :)

반응형

'Study ;3' 카테고리의 다른 글

[javascript] bootstrap-table export csv 문제  (0) 2021.01.13
[java] PKIX path building failed  (0) 2020.12.23
<a>의 download 속성 이슈  (0) 2020.11.30
mac os k8s  (0) 2020.10.04
Flask + Svelte + Rollup  (0) 2020.08.25
Comments