基于jquery ui 的下拉框搜索自动补全

combobox autocomplete based by jquery ui

基于jquery ui  的下拉框搜索自动补全
需要引入 jquery-ui.min.css 及 jquery-ui.min.js
参考地址:
http://www.runoob.com/jqueryui/example-autocomplete.html

js:

//url 自动匹配
(function( $ ) {

  $.widget( "custom.comboboxurl", {
  	
	 options:{
		
		url  : "",
		width :  200 ,
		readonly:false,
		textname:"",
		required:false
	 },
	 setreadonly:function(readonly){
		 
		 if(readonly != null && readonly != undefined){
			 this.options.readonly = readonly;
		 }
		 this.input.attr("readonly", this.options.readonly);
		 if(this.options.readonly){
			 this.downbtn.attr( "title", "" );
		 
 
		 }else{
			 this.downbtn.attr( "title", "显示所有选项" );
			  
		 }
	 },
	 setrequired:function(required){
		 
		 if(required != null && required != undefined){
			 this.options.required = required;
		 }
		 this.input.attr("required", this.options.required);
	 }
	 ,
	 setselect: function( value,text,trigger=false){
		 var temp = this;
		 if(text){
			 this.input.val(text); 
			 var option = $("<option value='"+ value + "' selected>"+ text +"</option>");
			 this.element.append(option);
			 if(trigger){
				 temp._trigger( "select", null, {
		              item: option
		         });
			 }
		 }else if(value){
			
			 var element = this.element;
			 var input =  this.input;
			 $.get(this.options.url,{id:value},function(json){
				 	element.find("option").remove();
		    		 
		    		$.each(json,function(i,n){
		    			var option = $("<option value='"+ n.value+ "'>"+ n.label +"</option>");
		    			element.append(option);
		    			input.val( n.label); 
		    			if(trigger){
			    			temp._trigger( "select", null, {
			    	              item: option
			    	        });
		    			}
		    		});
 
		     },"json");
		 }
	 }, 
    _create: function() {
  	  
      this.wrapper = $( "<span>" )
        .addClass( "custom-combobox" )
        .css("width",this.options.width+50)
        .insertAfter( this.element );
      
      this.element.hide();
      this._createAutocomplete();
      this._createShowAllButton();
      this.setreadonly();
      this.setrequired();
    },
    _createAutocomplete: function() {
      var selected = this.element.children( ":selected" ),
        value = selected.val() ? selected.text() : "";
      if(this.options.textname == ""){
    	  this.options.textname = this.element.attr("name")+"_text";
      }
      this.input = $( "<input>" )
        .appendTo( this.wrapper )
         .val( value )
        .attr( "title", "" )
        .attr("id",this.options.textname)
        .attr("name",this.options.textname)
        .css("width",this.options.width)
        .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
       .autocomplete({
          delay: 0,
          minLength: 0,
          source: $.proxy( this, "_source" )
        })
        .tooltip({
          tooltipClass: "ui-state-highlight"
        });

      this._on( this.input, {
    	  
        autocompleteselect: function( event, ui ) {
        	
           this.element.find(":selected").remove();
           ui.item.option.selected = true;
           ui.item.option.attr("selected",true);
           
          this._trigger( "select", event, {
            item: ui.item.option
          });
        },
        
        autocompletechange: "_removeIfInvalid"
      });
    },

    _createShowAllButton: function() {
      var input = this.input,
        wasOpen = false,
       temp = this;
      
      this.downbtn =  $( "<a>" );
      
      this.downbtn
        .attr( "tabIndex", -1 )
        .attr( "title", "显示所有选项" )
        .tooltip()
        .appendTo( this.wrapper )
        .button({
          icons: {
            primary: "ui-icon-triangle-1-s"
          },
          text: false
        })
        .removeClass( "ui-corner-all" )
        .addClass( "custom-combobox-toggle ui-corner-right" )
        .mousedown(function() {
          wasOpen = input.autocomplete( "widget" ).is( ":visible" );
        })
        .click(function() {
          if(temp.options.readonly)
        	  return;
          
          input.focus();

          // 如果已经可见则关闭
          if ( wasOpen ) {
            return;
          }

          // 传递空字符串作为搜索的值,显示所有的结果
          input.autocomplete( "search", "" );
        });
        
        
    },

    _source: function( request, response ) {
     
    	var element = this.element;
    	$.get(this.options.url,{keyword:request.term},function(json){
    		element.find(":not(:selected)").remove();
    		var array = new Array();
    		$.each(json,function(i,n){
    			var option = $("<option value='"+ n.value+ "'>"+ n.label +"</option>");
    			element.append(option);
    			array[i] = {value:n.label,lable:n.label,option:option};
    		});

    		response(array);
    	},"json");
    	
    	 
    	
    	//response();
    },

    _removeIfInvalid: function( event, ui ) {

      // 选择一项,不执行其他动作
      if ( ui.item ) {
        return;
      }

      // 搜索一个匹配(不区分大小写)
      var value = this.input.val(),
        valueLowerCase = value.toLowerCase(),
        valid = false;
      this.element.children( "option" ).each(function() {
        if ( $( this ).text().toLowerCase() === valueLowerCase ) {
          this.selected = valid = true;
          return false;
        }
      });

      // 找到一个匹配,不执行其他动作
      if ( valid ) {
        return;
      }

      // 移除无效的值
      this.input
        .val( "" )
        .attr( "title", value + " 没有匹配项" )
        .tooltip( "open" );
      this.element.val( "" );
      this._delay(function() {
        this.input.tooltip( "close" ).attr( "title", "" );
      }, 2500 );
      this.input.data( "ui-autocomplete" ).term = "";
    },

    _destroy: function() {
      this.wrapper.remove();
      this.element.show();
    }
  });
})( jQuery );

方法:
setreadonly 设置控件是否只读
setrequired 设置控件是否必填 基于html5 from
setselect 设置选中值
参数:
url : “”, 接口url
width : 200 , 控件宽度
readonly:false, 是否只读
textname:””, 对应文本域名称
required:false 是否必填
事件:
select 选择事件
js 调用方法:

$( "[name=user_id]" ).comboboxurl({width: 200 
		,url :"localhost/index.php?method=queryUser"
		,"required":true
		,select:function(event,item){
	     	console.dir(item);
		}
	});

php 接口方法:

    function queryUser($keyword = ""){
       
        $id = I("id",0);
        
        $users = D("users");
        if($id>0 ){
            
            $array = $users->where( " id = '$id' ")->select();
        }else{

            $array = $users->where( " user_nicename like '%$keyword%' ")->limit(0,10)->select();
            
        }
        
        $temp = array();
        foreach ($array as $row){
            
            $temp[] = array("value"=>$row["id"],"label"=>$row["user_nicename"]);
        }
        echo  json_encode($temp);
    }
/*autocomplate 部分样式*/
.custom-combobox {
  position: relative;
  display: inline-block;
	width:250px;
 }
.custom-combobox-toggle {
  position: absolute;
  top: 0;
  bottom: 0;
  margin-left: -1px;
  padding: 0;
  /* 支持: IE7 */
  *height: 1.7em;
  *top: 0.1em;
}
.custom-combobox-input {
	width:200px;
  margin: 0;
  padding: 0.3em;
}

发表评论

您的电子邮箱地址不会被公开。