하루종일 삽질한 끝에 내 프로젝트에 돌아가게끔 코딩을 완료했다..
애초에 자동완성기능의 개념이 부족했던터라 데이터를 어떻게 받아오고 어떻게 처리하는 감이 아예없었다.
그래서 가장먼저 깨달은 것(또는 현재까지 결론지은 것)은,
1. 자동완성의 원천데이터는 반드시 배열형태로 미리 저장이 되어있어야 한다!
-> 즉, api 호출로 그때그때 불러와서 자동완성을 하는 것이 아니라, 미리 배열형태를 프론트서버가 저장하는 것이다.
2. 저장된 배열을 제이쿼리 autocomplete으로 처리하는 것!
* 사실, 그때그때 불러와서 자동완성을 하는 방법도 있을 수도 있는데 지금의 나의 상황에서는 잘 모르겠다 ㅠㅠ
첫번째 방법 - 일반 배열로 자동완성 기능 구현
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<!-- 검색어를 입력할 input box 구현부분 -->
<input id="hd_search">
</body>
</html>
<script>
// 이미 저장된 배열형태로 진행
var sampleSrc = [{"product_id": 1,
"product_name": "신라면"},
{"product_id": 2,
"product_name": "진라면"},
{"product_id": 3,
"product_name": "열라면"},
{"product_id": 4,
"product_name": "삼양라면"},
{"product_id": 5,
"product_name": "불닭볶음면"},
{"product_id": 6,
"product_name": "라볶이"},
{"product_id": 7,
"product_name": "짜장라면"},
];
$("#hd_search").autocomplete({ //자동완성 시작
source : function(request, response){
var r = []; //자동완성의 응답값
var q = request.term; //사용자의 input값을 받는다
//배열의 형태가 복잡한 경우, 임의로 필터를 지정해줘야함
$.each(sampleSrc, function(k, v){
if (v.product_name.indexOf(q) != -1) {
r.push({
label: v.product_name, //자동완성창에 표시되는 데이터
value: v.product_name, //선택했을때 input박스에 입력되는 데이터
"product_id": v.product_id, //추가정보를 핸들링하고 싶을때 추가
})
}
});
response(r.slice(0,10)); //자동완성 최대갯수 제한
},
select : function(event, ui) { //아이템 선택시
console.log(ui.item);
console.log(ui.item.value);
},
focus : function(event, ui) {
return false;
},
minLength: 1,// 최소 글자수
autoFocus: true, //첫번째 항목으로 자동 포커스
delay: 0, //검색창에 글자 써지고 나서 autocomplete 창 뜰 때 까지 딜레이 시간(ms)
close : function(event){ //자동완성창 닫아질때 호출
//console.log(event);
}
});
</script>
두번째 방법 - ajax로 데이터를 불러온 후 자동완성 기능 구현
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<!-- 검색어를 입력할 input box 구현부분 -->
<input id="hd_search">
</body>
</html>
<script>
var searchSrc; //자동완성 원천데이터 저장을 위한 빈 배열
$.ajax({
url: "~~", //api GET할 url주소 입력.
type: "GET",
dataType: "json",
async: false, //ajax로 받아온 데이터를 변수에 저장하기위해 비동기를 false로 처리
success: function(res){
searchSrc = res.results; //성공시, 데이터를 변수에 저장
}
});
console.log(searchSrc); //저장된 변수 확인
$("#hd_search").autocomplete({ //자동완성 시작
source : function(request, response){
var r = []; //자동완성의 응답값
var q = request.term; //사용자의 input값을 받는다
//배열의 형태가 복잡한 경우, 임의로 필터를 지정해줘야함
//내가 받아온 배열이 위의 예제배열과 같은 형태이기때문에 데이터형태를 그대로 구현
$.each(searchSrc, function(k, v){
if (v.product_name.indexOf(q) != -1) {
r.push({
label: v.product_name, //자동완성창에 표시되는 데이터
value: v.product_name, //선택했을때 input박스에 입력되는 데이터
"product_id": v.product_id, //추가정보를 핸들링하고 싶을때 추가
})
}
});
response(r.slice(0,10)); //자동완성 최대갯수 제한
},
select : function(event, ui) { //아이템 선택시
console.log(ui.item);
console.log(ui.item.value);
},
focus : function(event, ui) {
return false;
},
minLength: 1,// 최소 글자수
autoFocus: true, //첫번째 항목으로 자동 포커스
delay: 0, //검색창에 글자 써지고 나서 autocomplete 창 뜰 때 까지 딜레이 시간(ms)
close : function(event){ //자동완성창 닫아질때 호출
//console.log(event);
}
});
</script>
배열을 필터링하는 로직은, 완전하게 이해하진 못했고 스택오버플로우에서 copy&paste로 구현하였다
https://stackoverflow.com/questions/49798936/jquery-autocomplete-how-to-filter-response-data
jQuery autocomplete how to filter response data
I have code setup like on this fiddle but autocomplete isn't filtering results while typing. jQuery(document).ready(function($) { var autocompleteTerms = JSON.parse( posts ); $('#post-s...
stackoverflow.com
개인적으로 정말 추천하는 글은, autocoplete 공식사이트의 source옵션에서 function 파트를 주의깊게 읽은 것이 도움이 많이 되었다.
https://api.jqueryui.com/autocomplete/#option-source
Autocomplete Widget | jQuery UI API Documentation
Description: Autocomplete enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering. Any field that can receive input can be converted into an Autocomplete, namely, elements, elements, and
api.jqueryui.com
개념적으로 정말 친절하게 알려준 블로그이다.
https://behabit.tistory.com/entry/jquery-autocomplete
[jquery] autocomplete
■ 참조 1. JQuery UI - Autocomplete jqueryui.com/autocomplete/ Autocomplete | jQuery UI Autocomplete Enables users to quickly find and select from a pre-populated list of values as they type, levera..
behabit.tistory.com
'javascript' 카테고리의 다른 글
[zingchart] javascript에서 워드클라우드 구현하기 (0) | 2022.05.30 |
---|---|
[chart.js] javascript에서 레이더차트 구현하기 (0) | 2022.05.12 |