본문 바로가기

Javascript/jQuery

검색어 자동완성 - jQuery Autocomplete 사용법 - 삽질중인 개발자

반응형

- jQuery autocomplete 사용법 및 옵션 정리 -

 

 

입력 필드에 타이핑을 하면 자동으로 남은 검색어를 완성해주는 기능을 jQuery UI 에서 이미 구현을 다 해놨다.

이것을 jQuery UI에서는 autocomplete 라고 부른다.

 

네이버 자동 완성 기능

 

사용방법

필요한 CSS , JS 파일

<!-- 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>
 

기본 사용 방법

우선 TEXT 영역부터 만들어야 한다.

<body>
    <!-- body 부분 -->
    <input id="searchInput">
</body>

 

1. 일반 배열 안에서 검색 방법

 

<script>
    $(function() {    //화면 다 뜨면 시작
        var searchSource = ["김치 볶음밥", "신라면", "진라면", "라볶이", "팥빙수","너구리","삼양라면","안성탕면","불닭볶음면","짜왕","라면사리" ]; // 배열 형태로 
        $("#searchInput").autocomplete({  //오토 컴플릿트 시작
            source : searchSource,    // source 는 자동 완성 대상
            select : function(event, ui) {    //아이템 선택시
                console.log(ui.item);
            },
            focus : function(event, ui) {    //포커스 가면
                return false;//한글 에러 잡기용도로 사용됨
            },
            minLength: 1,// 최소 글자수
            autoFocus: true, //첫번째 항목 자동 포커스 기본값 false
            classes: {    //잘 모르겠음
                "ui-autocomplete": "highlight"
            },
            delay: 500,    //검색창에 글자 써지고 나서 autocomplete 창 뜰 때 까지 딜레이 시간(ms)
//            disabled: true, //자동완성 기능 끄기
            position: { my : "right top", at: "right bottom" },    //잘 모르겠음
            close : function(event){    //자동완성창 닫아질때 호출
                console.log(event);
            }
        });
        
    });
</script>​

 

2. ajax 버전

스프링 컨트롤러 부분이다. 주석에 있는 JSON을 반환한다.

//스프링 컨트롤러 부분
@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에 저장 후 자동완성 기능 구현하는 코드

<script>
      $(function() {    //화면 다 뜨면 시작
        $("#searchInput").autocomplete({
            source : function( request, response ) {
                 $.ajax({
                        type: 'get',
                        url: "/json",
                        dataType: "json",
                        //data: {"param":"param"},
                        success: function(data) {
                            //서버에서 json 데이터 response 후 목록에 추가
                            response(
                                $.map(data, function(item) {    //json[i] 번째 에 있는게 item 임.
                                    return {
                                        label: item+"label",    //UI 에서 보여지는 글자, 실제 검색어랑 비교 대상
                                        value: item,    //그냥 사용자 설정값?
                                        test : item+"test"    //이런식으로 사용

                                        //[
                     //    {"name": "하늘이", "dogType": "푸들", "age": 1, "weight": 2.14},
                         //    {"name": "콩이", "dogType": "푸들", "age": 3, "weight": 2.5},
                         //    {"name": "람이", "dogType": "허스키", "age": 7, "weight": 3.1}
                         //]
                                        // json이 다음 처럼 넘어오면
                                        // 상황 : name으로 찾고 dogType을 넘겨야 하는 상황이면 
                                        // label : item.dogType ,    //오토컴플릿이 되고 싶은 단어 
                                        // value : item.family ,    //넘겨야 하는 단어
                                        // age : item.age ,
                                        // weight : item.weight
                                    }
                                })
                            );
                        }
                   });
                },    // source 는 자동 완성 대상
            select : function(event, ui) {    //아이템 선택시
                console.log(ui);//사용자가 오토컴플릿이 만들어준 목록에서 선택을 하면 반환되는 객체
                console.log(ui.item.label);    //김치 볶음밥label
                console.log(ui.item.value);    //김치 볶음밥
                console.log(ui.item.test);    //김치 볶음밥test
                
            },
            focus : function(event, ui) {    //포커스 가면
                return false;//한글 에러 잡기용도로 사용됨
            },
            minLength: 1,// 최소 글자수
            autoFocus: true, //첫번째 항목 자동 포커스 기본값 false
            classes: {    //잘 모르겠음
                "ui-autocomplete": "highlight"
            },
            delay: 500,    //검색창에 글자 써지고 나서 autocomplete 창 뜰 때 까지 딜레이 시간(ms)
//            disabled: true, //자동완성 기능 끄기
            position: { my : "right top", at: "right bottom" },    //잘 모르겠음
            close : function(event){    //자동완성창 닫아질때 호출
                console.log(event);
            }
        });
        
    });

</script>​

 

 

자동 완성 UI 부분 변경하는 방법

 

<script>    

    $(function() {    //화면 다 뜨면 시작
        $("#searchInput").autocomplete({
            source : function( request, response ) {
               
             //위에 있는 코드랑 동일 생략//
             
            
            }
        }).autocomplete( "instance" )._renderItem = function( ul, item ) {    //요 부분이 UI를 마음대로 변경하는 부분
                  return $( "<li>" )    //기본 tag가 li로 되어 있음 
                  .append( "<div>" + item.value + "<br>" + item.label + "</div>" )    //여기에다가 원하는 모양의 HTML을 만들면 UI가 원하는 모양으로 변함.
                  .appendTo( ul );
           };
    });
    
</script>

 

jQuery-ui autocomplete 도큐먼트 페이지

 

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

한글 초성 검색 기능 ▼

jQuery autocomplete 을 이용한 한글 초성 검색

 

jQuery autocomplete 한글 초성 검색

jQuery UI autocomplete 로 영어는 검색이 잘 되지만 한글의 경우는 잘 안된다. 예를 들면 한글에 대한 초성 검색이라든지 초.중.종성 검색이 autocomplete 에서는 지원이 잘 안되고 있다. ​ ajax를 이용해서 DB..

programmer93.tistory.com

 

반응형