[jQuery] autocomplete


autocomplete


1. 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>


2.기본 ꡬ쑰

var auto_source = [ 'apple', 'banana', 'chocolate' ];

$('#autoInputTag').autocomplete({
	source: auto_source
});


3.μœ μš©ν•œ 속성

- source / minLength / autofocus / select

var auto_source = [ 'apple', 'banana', 'chocolate' ];

$('#autoInputTag').autocomplete({
	source: auto_source,
	minLength: 2,
	autoFocus: true,
	select: function (event, ui) { }
});
sourceArray/String/Functionautocomplete에 μ‚¬μš©ν•  μ†ŒμŠ€ 데이터
minLengthInteger검색기λŠ₯을 ν™œμ„±ν™”ν•  μ΅œμ†Œ κΈ€μž 개수 값이 2λ©΄, 2κΈ€μžλ₯Ό μž…λ ₯ν•΄μ•Ό κ²€μƒ‰λœλ‹€
autoFocusbooleanμ†ŒμŠ€ λ°μ΄ν„°μ—μ„œ κ²€μƒ‰ν–ˆμ„ λ•Œ 맨 μœ„ 데이터에 μžλ™ 포컀슀
selectFunctionautocompleteμ—μ„œ μ‚¬μš©μžκ°€ 데이터λ₯Ό μ„ νƒν–ˆμ„ λ•Œ 이벀트


4.방법1

λͺ©ν‘œ: μƒμœ„ Select λ°•μŠ€μ—μ„œ μ„ νƒν•œ ν•­λͺ©μ— 따라 λ‹€λ₯Έ μ†ŒμŠ€ 데이터 λ°”μΈλ”©ν•˜κΈ°

var data = {
	'bird': [ 'fly', 'sit', 'tweet', 'sing', 'eat worm' ],
  'dog': [ 'bark', 'run', 'follow', 'sleep' ]
}

$('#action').autocomplete({
	source : data['bird']
});

$('#animal').change(function() {
	var animal = $(this).val();
  $('#action').autocomplete('option', 'source', data[animal]);
});


5.방법 2

λͺ©ν‘œ: input에 κ²€μƒ‰ν•˜λŠ” ν‚€μ›Œλ“œμ™€ μ‹€μ œ 검색 μ™„λ£Œν–ˆμ„ λ•Œ input에 보여쀄 κ°’ λΆ„λ¦¬ν•˜κΈ°

var data = {
	'bird': [ 
 		{ label: 'Fly', value: 'fly' }, 
  		{ label: 'Sit', value: 'sit' },
		{ label: 'Tweet', value: 'tweet' },
 		{ label: 'Sing', value: 'sing' },
 		{ label: 'Eat', value: 'eat worm' }
 	],
 	'dog': [ 
  		{ label: 'Bark', value: 'bark' },
		{ label: 'Run', value: 'run' },
		{ label: 'Follow', value: 'follow' },
		{ label: 'Sleep', value: 'sleep' }
	]
}

$('#action').autocomplete({
	source : data['bird']
});

$('#animal').change(function() {
	var animal = $(this).val();
  $('#action').autocomplete('option', 'source', data[animal]);
});


6. 방법 3

λͺ©ν‘œ: 검색어 μ™„μ„±λ˜λŠ” 타이밍에 ν•˜λ‹¨μ— λ¬Έμž₯으둜 ν‘œμ‹œν•˜κΈ° (select ν™œμš©μ•ˆ)

var data = {
	'bird': [ 
  	{ label: 'Fly', value: 'fly', 'id': 0 }, 
    { label: 'Sit', value: 'sit', 'id': 1 },
    { label: 'Tweet', value: 'tweet', 'id': 2 },
    { label: 'Sing', value: 'sing', 'id': 3 },
    { label: 'Eat', value: 'eat worm', 'id': 4 }
  ],
  'dog': [ 
  	{ label: 'Bark', value: 'bark', 'id': 5 },
    { label: 'Run', value: 'run', 'id': 6 },
    { label: 'Follow', value: 'follow', 'id': 7 },
    { label: 'Sleep', value: 'sleep', 'id': 8 }
	]
}

$('#action').autocomplete({
      source: function (request, response) {
                var term = request.term; // search keyword
                var filteredData = data['bird'].filter(x => (x.label.indexOf(term) >= 0));
                response($.map(filteredData, function (item) {
                    return {
                        label: item.label,
                        value: item.value,
                        'data-id': item.id
                    }
                }))
            },
    autoFocus: true,
    select: function(event, ui) {
        $('#sentence').text(`${ui.item['data-id']} ${ui.item.value}`);
  }
});

$('#animal').change(function() {
	var animal = $(this).val();
  var source = data[animal];
  $('#action').autocomplete('option', 'source', function (request, response) {
  							var term = request.term; // search keyword
                var filteredData = source.filter(x => (x.label.indexOf(term) >= 0));
                response($.map(filteredData, function (item) {
                    return {
                        label: item.label,
                        value: item.value,
                        'data-id': item.id
                    }
                }))
            });
});


7. 방법 4

idλ₯Ό κΈ°μ€€μœΌλ‘œ autocomplete κΈ°λŠ₯을 μ„ μ–Έ ν•΄μ€λ‹ˆλ‹€.

$("#testInput").autocomplete({
        source : function(request, response) {
            $.ajax({
                  url : "/get/test"
                , type : "GET"
                , data : {keyWord : $("#testInput").val()} // 검색 ν‚€μ›Œλ“œ
                , success : function(data){ // 성곡
                    response(
                        $.map(data, function(item) {
                            return {
                                  label : item.testNm    //λͺ©λ‘μ— ν‘œμ‹œλ˜λŠ” κ°’
                                , value : item.testNm    //선택 μ‹œ input창에 ν‘œμ‹œλ˜λŠ” κ°’
                                , idx : item.testIdx    // db 인덱슀λ₯Ό λ‹΄μ„μˆ˜ 있음 
                            };
                        })
                    );    //response
                }
                ,
                error : function(){ //μ‹€νŒ¨
                    alert("톡신에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€.");
                }
            });
        }
        , minLength : 1    
        , autoFocus : false    
        , select : function(evt, ui) {
            console.log("전체 data: " + JSON.stringify(ui));
            console.log("db Index : " + ui.item.idx);
            console.log("검색 데이터 : " + ui.item.value);
        }
        , focus : function(evt, ui) {
            return false;
        }
        , close : function(evt) {
        }
    });

β€» 이벀트 μ„€λͺ…

- source : input ν•„λ“œμ— νƒ€μ΄ν•‘μ‹œ λ™μž‘ν•©λ‹ˆλ‹€.

- minLength : 쑰회λ₯Ό μœ„ν•œ μ΅œμ†Œ κΈ€μžμˆ˜μž…λ‹ˆλ‹€.

- autoFocus : 첫번째 ν•­λͺ© μžλ™ 포컀슀(κΈ°λ³Έκ°’ : false)

- select : 검색 λ¦¬μŠ€νŠΈμ—μ„œ ν•΄λ‹Ή ν•„λ“œ μ„ νƒμ‹œ select μ΄λ²€νŠΈκ°€ λ°œμƒν•©λ‹ˆλ‹€.

- focus : ν•œκΈ€ 였λ₯˜ λ°©μ§€μž…λ‹ˆλ‹€.

- close : λ¦¬μŠ€νŒ… 창이 λ‹«νžλ•Œ λ°œμƒν•˜λŠ” 이벀트 μž…λ‹ˆλ‹€.