select2动态添加option

背景

select2 使用ajax remote加载数据方式时,不能使用$('#select2').val();的形式获取option的value,为了统一代码风格,需要把请求接口返回的结果以option的形式动态添加到select2组件上。

html

<select id="userSelect" name="userSelect" class="form-control" style="width: 150px"> </select>

原来的实现

javascirpt实现
function initSelect(stable,type) {
    $('#userSelect').select2({
		placeholder : '选择用户',
		minimumResultsForSearch : -1,// 不展示搜索框
		ajax : {
		    url : "/user/list",
		    type : 'get',
		    dataType : 'json',
	        data : {
		    'stable' : stable,
		    'type' : type
			},
		    processResults : function(data) {
				// 是否隐藏稳定环境的选项
				var jsonData = data['respData'];
			
				return {
			    	results : $.map(jsonData, function(item) {
						var i = 1;
						return {
				  	  		text : item,
				  	  		id : i++
						}
			    	})
				};
		    },
		}
    });
 }
后端接口返回
{"respCode":10001,"respMsg":"获取用户列表成功","respData":["张三","李四","王五"]}
取值
var user = $("#select2-userSelect-container").text();

修改后

javascript实现
function initSelect(showStable, type) {
    $('#userSelect').select2();
    $('#userSelect').val(null).trigger('change');// 加载静态框时先清空。
    $.ajax({
		url : "/user/list",
		type : 'get',
		async : false,
		data : {
		    'stable' : stable,
		    'type' : type
		},
		dataType : 'json',
		success : function(data) {
		    var jsonData = data['respData'];
		    console.log(jsonData);
		    $.each(jsonData, function(i) {
			// create the option and append to Select2
			var option = new Option(jsonData[i].text, jsonData[i].id, true, true);
			$('#userSelect').append(option);
		    });
		    $('#userSelect').trigger("change");
		},
    });
}
后端接口返回结果
{"respCode":10001,"respMsg":"获取用户列表成功","respData":[{"id":"zhangsan","text":"张三"},{"id":"lisi","text":"李四"}]}
取值
var user= $("#userSelect").val();

结论

修改后,取值方式更方便,可以获取到后端接口返回的id值。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值