일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 스프링 부트
- Deep Learning
- jQuery
- annotation
- data structure
- 하이브리드앱
- kotlin
- log4j2
- Machine Learning
- spring boot
- spring
- 테스트 커버리지
- Java
- react
- transformer
- 리액트
- 제이쿼리
- C++
- bean
- 자바스크립트
- AWS
- ES6
- Test Coverage
- 자료구조
- 구버전
- 어노테이션
- 스프링
- javascript
- JPA
- cache
- Today
- Total
박서희연구소
[jQuery] 제이쿼리 Autocomplete(자동완성) 사용법 및 옵션 살펴보기 본문
[jQuery] 제이쿼리 Autocomplete(자동완성) 사용법 및 옵션 살펴보기
SEOHUI PARK 2020. 2. 23. 01:40[문제]
개발하는 쇼핑몰 프로젝트의 Front 단 검색창 개발 중 Autocomplete(자동완성) 기능이 필요하다.
[목표]
jQuery 의 Autocomplete 기능을 적용해본다.
Autocomplete
입력 필드에 타이핑 시 자동으로 남은 검색어를 완성해 표시해 주는 기능을 보통 자동완성 이라고 하는데,
이러한 기능을 jQuery UI 에서 이미 구현을 해놨는데, Autocomplete 라고 부른다.

[해결]
환경 : JQuery 라이브러리
사용 방법 및 구현 방법
필요한 css 및 js 파일
<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>
html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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="searchBox">
</body>
</html>
1. 배열 안에서 사용법
JavaScript)
// 배열을 선언하여 사용하는 방식
$(function() {
var searchSource = ['엽기떡볶이', '신전떡볶이', '걸작떡볶이', '신당동떡볶이']; // 배열 생성
$('#searchBox').autocomplete({ // autocomplete 구현 시작부
source : searchSource, //source 는 자동완성의 대상
select : function(event, ui) { // item 선택 시 이벤트
console.log(ui.item);
},
focus : function(event, ui) { // 포커스 시 이벤트
return false;
},
minLength : 1, // 최소 글자 수
autoFocus : true, // true로 설정 시 메뉴가 표시 될 때, 첫 번째 항목에 자동으로 초점이 맞춰짐
classes : { // 위젯 요소에 추가 할 클래스를 지정
'ui-autocomplete' : 'highlight'
},
delay : 500, // 입력창에 글자가 써지고 나서 autocomplete 이벤트 발생될 떄 까지 지연 시간(ms)
disable : false, // 해당 값 true 시, 자동완성 기능 꺼짐
position : { my : 'right top', at : 'right bottom'}, // 제안 메뉴의 위치를 식별
close : function(event) { // 자동완성 창 닫아질 때의 이벤트
console.log(event);
}
});
});
2. ajax 를 활용한 사용법
Java)
// 컨트롤러 부분
@RequestMapping(value = "/json", method = RequestMethod.GET, produces="text/plain;charset=UTF-8")
@ResponseBody
public String json(Locale locale, Model model) {
String[] array = {"엽기떡볶이", "신전떡볶이", "걸작떡볶이", "신당동떡볶이"}; // 배열 생성
Gson gson = new Gson();
return gson.toJson(array); // 배열 반환
}
받아온 JSON 을 Map 에 저장 후 자동완성 기능 구현 코드
JavaScript)
$(function() {
$('#searchBox').autocomplete({
source : function(reuqest, response) {
$.ajax({
type : 'get',
url: '/json',
dataType : 'json',
success : function(data) {
// 서버에서 json 데이터 response 후 목록 추가
response(
$.map(data, function(item) {
return {
label : item + 'label',
value : item,
test : item + 'test'
}
})
);
}
});
},
select : function(event, ui) {
console.log(ui);
console.log(ui.item.label);
console.log(ui.item.value);
console.log(ui.item.test);
},
focus : function(event, ui) {
return false;
},
minLength : 1,
autoFocus : true,
classes : {
'ui-autocomplete': 'highlight'
},
delay : 500,
position : { my : 'right top', at : 'right bottom' },
close : function(event) {
console.log(event);
}
});
});
자동완성 UI 부분 변경하는 코드
JavaScript)
$(function() {
$('#searchBox').autocomplete({
source : function(request, response) {
$.ajax({
type : 'get',
url: '/json',
dataType : 'json',
success : function(data) {
// 서버에서 json 데이터 response 후 목록 추가
response(
$.map(data, function(item) {
return {
label : item + 'label',
value : item,
test : item + 'test'
}
})
);
}
});
}
}).autocomplete('instance')._renderItem = function(ul, item) { // UI 변경 부
return $('<li>') //기본 tag가 li
.append('<div>' + item.value + '<br>' + item.label + '</div>') // 원하는 모양의 HTML 만들면 됨
.appendTo(ul);
};
});
결과)

- 끝 -
출처 및 참고 :
https://api.jqueryui.com/autocomplete/#method-_renderItem
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://programmer93.tistory.com/2
검색어 자동완성 - jQuery Autocomplete 사용법 - 개발자 삽질 일기
- jQuery autocomplete 사용법 및 옵션 정리 - 입력 필드에 타이핑을 하면 자동으로 남은 검색어를 완성해주는 기능을 jQuery UI 에서 이미 구현을 다 해놨다. 이것을 jQuery UI에서는 autocomplete 라고 부른다...
programmer93.tistory.com
'○ Programming [Web] > jQuery' 카테고리의 다른 글
[jQuery] 제이쿼리 Select box(셀렉트 박스) 선택 값 제어 방법 (0) | 2020.02.19 |
---|---|
[jQuery] 제이쿼리 클래스(Class) 변경 및 추가, 제거 방법 (0) | 2020.02.18 |