'[jQuery 기본 강좌]1-3 jquery 자동완성 autocomplete 기능 쉽게 적용하기'에 해당되는 글 1건

  1. 2010.10.19 [jQuery 기본 강좌]1-3 jquery 자동완성 autocomplete 기능 쉽게 적용하기
반응형
 


네이버나 포탈사이트 등을 방문 하다보면 위와같이

앞글자 혹은 중간글자만 쳐도 나머지 글자들이 나오는 화면을 볼수있는데

이를 자동완성기능 혹은 autocomplete 라고 한다..

기본적으로 브라우저내에서 자동완성기능을 지원하긴 하지만

DB와 연동해서 뿌려주는 기능은 별도 제작을 해야한다.

캐릭터셋이 utf-8 이냐 euc kr 이냐에 따라서도 사용방법이 약간은 다르다.

아래는 간단한 예제와 샘플파일이다.


위 파일은 autocomplete 기능을 사용하게 해주는 plug in 이며

jquery.com 의 plugins 에서도 다운이 가능하다.

우선 jquery 스크립트를 넣어준 뒤 위 플러그인을 삽입해주면 된다.

<?include "data_js.php";?>

<SCRIPT type="text/javascript" src="../jquery/jquery-1.4.2.min.js"></script>
<link rel="stylesheet" type="text/css" href="./autocomplete/jquery.autocomplete.css"/>
<script type="text/javascript" src="./autocomplete/jquery.autocomplete.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $("#search").autocomplete(goods,{
  matchContains: true
 });
});
</script>

<input type="text" id="search" autocomplete="off">

* 상세소스는 http://jaweb.co.kr/jstudy/18.php 접속후 소스보기하면 다 나오는데
위의 소스만으로도 구동에는 전혀 문제가 없다.


위 내용은 search 라는 id 필드는 autocomplete 기능을 사용할 것이고

데이터는 goods 데이터를 기반으로 내용중 일부라도 맞는경우 (matchContains: true)

보여지게 하겠다는 속성이다.

데이터(goods)를 가져올때는 여러가지 방법이 있는데

난 DB에서 데이터 이용방법과 js 파일 생성방식 두가지로 선택했다.


data_js.php 파일은  단순하게 파일내에 입력을 하게되면 알아서 적용된다. (내용이 간단하니 파일을 참고하면 좋다.)


data_db.php 파일은 db셋팅이 되어있는 파일내에서 어느부분인지를 선택 한 뒤 작업을 해주면 된다.

헌데 소스내용을 보면 굳이 urlencode 를 해서 array_push로 배열안에 값을 넣고

실제 뿌려줄때는 urldecode 를 해서 json 방식으로 다시 인코딩 한 뒤 값을 뿌려준다.

urlencode 의 사용목적은 바로 한글문제..

utf-8 환경에선 urlencode 없이도 무리없이 정상작동 하지만

euckr 환경에선 글씨가 깨져서 들어가거나

null값으로 출력이되어 오류가 나게 된다.


그럴때 json으로 인코딩을 하기 전 urlencode 로 한번 인코딩을 해주고

실제 뿌려줄때 decode를 안하게되면 %45%D 이런식으로 문자가 깨져서 보이기에

글씨 깨짐을 방지하기 위해서 위와같이 작업을 한것이다.


autocomplete 플러그인 내에서는 지원하는 기능이 내가 설명한 정도보다는 훨씬 많다.

줄에 맞춰서 값을 가져오거나

key값에 따라 값을 뿌려주는 기능...

이미지를 이용 출력해는 기능 등~   (참고 : http://jaweb.nayana.com/search.php   우측상단 펫 검색란에 1,2 등을 치거나 펫 이름을 치면 결과가 나오는데.. jquery 처음 배울때 작업한 것이라 소스가 상당히 조잡한 편이다.)

쓸데가 상당히 많아보이는 플러그인이니 공부할때 참고하면 좋을 것 같다.


출처 : http://jaweb.tistory.com/159

------------------------------------------------------

Ajax AutoComplete for jQuery

AutoComplete is like Magic!

Ajax Autocomplete for jQuery allows you to easily create autocomplete/autosuggest boxes for text input fields.

It is built with focus on performance. Results for every query are cached and pulled from local cache for the same repeating query. If there are no results for particular query it stops sending requests to the server for other queries with the same root.

Demo

Ajax autosuggest sample (start typing country name):


Local(no ajax) autosuggest sample (start typing month name):

Suggest:   

Note: Delimiter support has been added in v1.0.5. Try separate countries by "," or ";".

What's New in 1.1

$('#query').autocomplete(options) now returns an Autocomplete instance only for the first matched element.

Autocomplete functionality can be disabled or enabled programmatically.

var ac = $('#query').autocomplete(options);
ac.disable();
ac.enable();

Options can be changed programmatically at any time, only options that are passed get set:

ac.setOptions({ zIndex: 1001 });

If you need to pass additional parameters, you can set them via setOptions too:

ac.setOptions({ params: { first:'John', last:'Doe' } });

New parameters when initializing autocomplete. They can also be set via setOptions.

- zIndex: default value is 9999.

- fnFormatResult: function that formats values that are displayed in the autosuggest list. It takes three parameters: suggested value, data and current query value. Default function for this:

var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');

function fnFormatResult(value, data, currentValue) {
  var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
  return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
}

Installation

Include jQuery in your header. After its included, add autocomplete script.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>

How to Use

Here is an Ajax Autocomplete sample for the text field with id "query"

<input type="text" name="q" id="query" />

Create an instance of the Autocomplete object. You can have multiple instances on a single page.

Important: Autocomplete must be initialized after DOM has finished loading. Otherwise you will get an error in IE.

var options, a;
jQuery(function(){
  options = { serviceUrl:'service/autocomplete.ashx' };
  a = $('#query').autocomplete(options);
});

You can add extra options:

  var a = $('#query').autocomplete({ 
    serviceUrl:'service/autocomplete.ashx',
    minChars:2, 
    delimiter: /(,|;)\s*/, // regex or character
    maxHeight:400,
    width:300,
    zIndex: 9999,
    deferRequestBy: 0, //miliseconds
    params: { country:'Yes' }, //aditional parameters
    noCache: false, //default is false, set to true to disable caching
    // callback function:
    onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); },
    // local autosugest options:
    lookup: ['January', 'February', 'March', 'April', 'May'] //local lookup values 
  });

Use lookup option only if you prefer to inject an array of autocompletion options, rather than sending Ajax queries.

Web page that provides data for Ajax Autocomplete, in our case autocomplete.ashx will receive GET request with querystring ?query=Li, and it must return JSON data in the following format:

{
 query:'Li',
 suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
 data:['LR','LY','LI','LT']
}

Notes:

  • query - original query value
  • suggestions - comma separated array of suggested values
  • data (optional) - data array, that contains values for callback function when data is selected.

Styling

Script generates the following HTML (sample query Li). Active element when you navigate up and down is marked with class "selected". You can style it any way you wish.

<div class="autocomplete-w1">
  <div style="width:299px;" id="Autocomplete_1240430421731" class="autocomplete">
    <div><strong>Li</strong>beria</div>
    <div><strong>Li</strong>byan Arab Jamahiriya</div>
    <div><strong>Li</strong>echtenstein</div>
    <div class="selected"><strong>Li</strong>thuania</div>
  </div>
</div>

Here is style used in the sample above:

.autocomplete-w1 { background:url(img/shadow.png) no-repeat bottom right; position:absolute; top:0px; left:0px; margin:6px 0 0 6px; /* IE6 fix: */ _background:none; _margin:1px 0 0 0; }
.autocomplete { border:1px solid #999; background:#FFF; cursor:default; text-align:left; max-height:350px; overflow:auto; margin:-6px 6px 6px -6px; /* IE6 specific: */ _height:350px;  _margin:0; _overflow-x:hidden; }
.autocomplete .selected { background:#F0F0F0; }
.autocomplete div { padding:2px 5px; white-space:nowrap; overflow:hidden; }
.autocomplete strong { font-weight:normal; color:#3399FF; }

If you will use this CSS, please make sure to correct path to the shadow.png image. Image is included in the package. It uses CSS Drop Shadow technique by Sergio Villarreal.

Download

Download Ajax AutoComplete for jQuery

Download DevBridge Ajax Autocomplete v1.1.3 for jQuery

Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.

Currently supported browsers: IE 7+, FF 2+, Safari 3+, Opera 9+


Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Posted by 1010