jquery combobox下拉及异步加载数据

记录:

通常会遇到加载很多条数据到下拉框中,通过ajax的异步加载方法实现,参考jquery ui 官网

定义一个html标签

监控类型

加载js和css文件




自定义css样式

.ui-combobox {
	position: relative;
	display: inline-block;
}

.ui-combobox-toggle {
	position: absolute;
	top: 0;
	bottom: 0;
	margin-left: -1px;
	padding: 0;
	/* adjust styles for IE 6/7 */
	*height: 1.7em;
	*top: 0.1em;
}

.ui-combobox-input {
	margin: 0;
	padding: 0.3em;
}
jquery combobox封装代码,来自 jquery ui 官网

/**
 * 自定义ui combobox
 */

	(function( $ ) {
		$.widget( "ui.combobox", {
			_create: function() {
				var input,
					that = this,
					select = this.element.hide(),
					selected = select.children( ":selected" ),
					value = selected.val() ? selected.text() : "",
					wrapper = this.wrapper = $( "" )
						.addClass( "ui-combobox" )
						.insertAfter( select );

				function removeIfInvalid(element) {
					var value = $( element ).val(),
						matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( value ) + "$", "i" ),
						valid = false;
					select.children( "option" ).each(function() {
						if ( $( this ).text().match( matcher ) ) {
							this.selected = valid = true;
							return false;
						}
					});
					if ( !valid ) {
						// remove invalid value, as it didn't match anything
						$( element )
							.val( "" )
							.attr( "title", value + " 未找到任何匹配项" )
							.tooltip( "open" );
						select.val( "" );
						setTimeout(function() {
							input.tooltip( "close" ).attr( "title", "" );
						}, 2500 );
						input.data( "autocomplete" ).term = "";
						return false;
					}
				}

				input = $( "" )
					.appendTo( wrapper )
					.val( value )
					.attr( "title", "" )
					.addClass( "ui-state-default ui-combobox-input" )
					.autocomplete({
						delay: 0,
						minLength: 0,
						source: function( request, response ) {
							var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
							response( select.children( "option" ).map(function() {
								var text = $( this ).text();
								if ( this.value && ( !request.term || matcher.test(text) ) )
									return {
										label: text.replace(
											new RegExp(
												"(?![^&;]+;)(?!<[^<>]*)(" +
												$.ui.autocomplete.escapeRegex(request.term) +
												")(?![^<>]*>)(?![^&;]+;)", "gi"
											), "$1" ),
										value: text,
										option: this
									};
							}) );
						},
						select: function( event, ui ) {
							ui.item.option.selected = true;
							that._trigger( "selected", event, {
								item: ui.item.option
							});
						},
						change: function( event, ui ) {
							if ( !ui.item )
								return removeIfInvalid( this );
						}
					})
					.addClass( "ui-widget ui-widget-content ui-corner-left" );

				input.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "
  • " ) .data( "item.autocomplete", item ) .append( "" + item.label + "" ) .appendTo( ul ); }; $( "" ) .attr( "tabIndex", -1 ) .attr( "title", "显示所有" ) .tooltip() .appendTo( wrapper ) .button({ icons: { primary: "ui-icon-triangle-1-s" }, text: false }) .removeClass( "ui-corner-all" ) .addClass( "ui-corner-right ui-combobox-toggle" ) .click(function() { // close if already visible if ( input.autocomplete( "widget" ).is( ":visible" ) ) { input.autocomplete( "close" ); removeIfInvalid( input ); return; } // work around a bug (likely same cause as #5265) $( this ).blur(); // pass empty string as value to search for, displaying all results input.autocomplete( "search", "" ); input.focus(); }); input .tooltip({ position: { of: this.button }, tooltipClass: "ui-state-highlight" }); }, destroy: function() { this.wrapper.remove(); this.element.show(); $.Widget.prototype.destroy.call( this ); } }); })( jQuery );

  • 只需在页面加载的时候调用即可,实现了combobox的select事件的使用,同时也兼具了jquery autocomplete combobox的效果;

    	$(function() {
    		$("#s_type").combobox({
    			selected : function(event,ui){
    				var flag = $("#s_type option:selected").val();//获取当前选中value
    				if(flag==1){
    					doSearch();
    				}
    				else{
    					doSearch2();
    				}
    			}
    		});
    		
    	});

    效果图:







    实现异步加载数据的代码:

    	function loadCombobox(obj1,obj2){
    		//加载autocomplete
    		$.ajax({
    			type : "POST",
    			url : url地址,
    			dataType : "json",
    			cache : false,
    			async : false,
    			data : {
    				"param1" : 输入的字符参数,
    			},
    			success : function(json) {
    				var data = eval(json);//json数组
    
    				var optionStr = '';
    				for (var i = 0; i < data.length; i++) {
    					optionStr += "";
    				}
    				$("#" + obj2).html("" + optionStr);
    			}
    		});
    		$("#"+obj2).combobox();
    	};
    后台返回json格式数据:

                //用于异步ajax加载线路下拉列表
                String param1 = URLDecoder.decode(request.getParameter("param1") == null ? "-1" : request.getParameter("param1").trim(), "utf-8");
                JSONArray jsonArray = new JSONArray();
                JSONObject jsonObject = new JSONObject();
                BaseService service = new BaseService();
                List list = service.getlist(Long.parseLong(param1));
                if (list != null)
                {
                    for (int i = 0; i < list.size(); i++)
                    {
                        Table t = (Table)list.get(i);
                        jsonObject.put("id", t.getId());
                        jsonObject.put("name", t.getName());
                        jsonArray.add(jsonObject);
                    }
                }
                PrintWriter pw = null;
                StringBuffer sb = new StringBuffer();
                sb.append(jsonArray.toString());
                try
                {
                    response.setContentType("text/html;charset=GBK");
                    pw = response.getWriter();
                    pw.write(sb.toString());
                    pw.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }

    效果同上


    你可能感兴趣的:(Java,Web)