jQuery autocomplete应用

    项目应用上要对原来的一些input控件加上联想输入的功能,如下图所示:

jQuery_autoComplete_1.PNG

[图1:在文字输入框输入,会触发autocomplete控件的loading]

jQuery_autoComplete_2.PNG

[图2:在查询到数据后,把匹配结果显示出来]

 

    为了实现上面的功能,本着简单+熟悉的原则,我打算用jquery来实现,正好一查就找到了jQuery的autocomplete

    发现这个UI Widget用起来很简单,只有简单几个参数便可以实现我要的功能了。

jQuery("#InputID").autocomplete({
    source: ,
    minLength: ,
    delay: ,
    disable: 
});
  1. source: 可以是string,数组或者是自定义的方法,如通过ajax方式从后台取的数据,也可以是后台action的url
  2. minLength: 是指用户输入几个字符后触发autocomplete,默认是1
  3. delay: 是指用户输入字符多少毫秒后触发autocomplete,默认是300ms,这个数值设置的太大会半天没响应,设置的太小而且数据源是后台action的话,又会容易引发频繁的load
  4. disable: true | false,Disables (true) or enables (false) the autocomplete. Can be set when initialising (first creating) the autocomplete.

 

    我的要求是source从后台取数据,后台返回的json数据格式,所以source我设置如下:

    source: function( request, response ) {
        jQuery.ajax({
            url: "ajaxAction.do",
            data: "siteID=" + siteID + "&userName=" + request.term,
            type : "GET",
            dataType: "json",
            success: function( data ) {
                response( $.map( data, function( item ) {
                    return {
                        label: item,
                        value: item
                    }
                }));
            }
        });
    },

    注意这里我是用jQuery.ajax()来提交数据的,这里的request.term是用户输入的字符,本例图中是”hill”。指定返回的数据格式为json,然后把json数组里的每项显示在下拉框里,因为我要显示的文字和value是一样的,所label: item, value: item。这里的ajaxAction.do返回的数据是:

["hill","hillmans","hillp"]

全部代码如下:

jQuery("#keytextInput").autocomplete({
    source: function( request, response ) {
        jQuery.ajax({
            url: "ajaxGetCorUser.do",
            data: "siteID=" + siteID + "&userName=" + request.term,
            type : "GET",
            dataType: "json",
            success: function( data ) {
                response( $.map( data, function( item ) {
                    return {
                        label: item,
                        value: item
                    }
                }));
            }
        });
    },
    minLength: 2,
    delay: 500,
    disable: true
});

哦,不要忘记jquery.autocomplete.js,还有jquery.ui.autocomplete.css,然后根据项目的需要自己修改css样式即可。

在css里增加下面的语句,可以增加loading效果,另外防止返回的数据过大而加上了maxHeight

.ui-autocomplete-loading { background: white url('../images/wait-blue.gif') right center no-repeat; }

.ui-autocomplete {max-height: 100px; overflow-y: auto;}
/* IE 6 doesn't support max-height
 * we use height instead, but this forces the menu to always be this tall
 */
* html .ui-autocomplete {height: 100px;}
posted @ 2010-09-26 14:15  lettoo  阅读(2448)  评论(2编辑  收藏  举报