박서희연구소

[jQuery] 제이쿼리 Autocomplete(자동완성) 사용법 및 옵션 살펴보기 본문

○ Programming [Web]/jQuery

[jQuery] 제이쿼리 Autocomplete(자동완성) 사용법 및 옵션 살펴보기

SEOHUI PARK 2020. 2. 23. 01:40
반응형

[문제]

개발하는 쇼핑몰 프로젝트의 Front 단 검색창 개발 중 Autocomplete(자동완성) 기능이 필요하다.

[목표]

jQueryAutocomplete 기능을 적용해본다.

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); // 배열 반환
}

 

받아온 JSONMap 에 저장 후 자동완성 기능 구현 코드

 

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

 

반응형
Comments