jquery combobox下拉及异步加载数据

记录:

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

定义一个html标签

监控类型<select id="s_type"><option value="1" selected="selected">RFID</option><option value="2">视频</option></select>

加载js和css文件

<link rel="stylesheet" type="text/css" href="../jquery/css/jquery.ui.all.css">
<script type="text/javascript" src="../jquery/jquery-1.8.3.js"></script>
<script type="text/javascript" src="../jquery/jquery-ui.js"></script>

自定义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 = $( "<span>" )
						.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 = $( "<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"
											), "<strong>$1</strong>" ),
										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 $( "<li>" )
						.data( "item.autocomplete", item )
						.append( "<a>" + item.label + "</a>" )
						.appendTo( ul );
				};

				$( "<a>" )
					.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 += "<option value=\"" + data[i].id + "\" >"
							+ data[i].name + "</option>";
				}
				$("#" + obj2).html("<option value='-1'>--请选择--</option>" + 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();
            }

效果同上


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值