select2搜索選擇給多個文本框賦值

1、先看效果圖

 

2、 代碼實現

前端頁面實現

  1. orderFormAdd.html
<div class="wrapper wrapper-content animated fadeInRight ecommerce">
	<div class="row">
		<form class="form-horizontal" id="orderFormAddForm" method="post">
			<div class="form-group hidden">
            	<label class="col-lg-2 control-label">ID</label>
                <div class="col-lg-3">
                	<input type="text" class="form-control" name="id"/>
                </div>
            </div>
			<div class="form-group">
            	<label class="col-lg-2 control-label"><span class="text-danger">*</span> 客戶名稱</label>
                <div class="col-lg-3">
                	<select class="form-control" name="customerId" id="customerId_POP">
               		</select>
                </div>
            </div>
            <div class="form-group">
				<label class="col-lg-2 control-label"><span class="text-danger">*</span> 客戶電話</label>
                <div class="col-lg-3">
                	<input type="text" class="form-control" name="phoneNumber" id="phoneNumber_POP"/>
                </div>
				<label class="col-lg-3 control-label"> 送貨日期</label>
                <div class="col-lg-3">
                	<div class="input-group date">
						<input type="text" class="form-control _searchDate" name="deliveryDate" id="deliveryDate"/><span class="input-group-addon"><i class="fa fa-calendar"></i></span>
					</div>
                </div>
            </div>
            <div class="form-group">
				<label class="col-lg-2 control-label"><span class="text-danger">*</span> 送貨地址</label>
                <div class="col-lg-9">
					<input type="text" class="form-control" name="address" id="address_POP"/>
                </div>
            </div>
			<div class="form-group">
                <div class="col-lg-offset-2 col-lg-10">
                    <button class="btn btn-primary" type="button" id="orderFormAddSave"><i class="fa fa-save"></i>&nbsp;&nbsp;保存</button>
                    <button class="btn btn-default" type="button" id="orderFormAddClose"><i class="fa fa-times"></i>&nbsp;&nbsp;關閉</button>
                </div>
            </div>
		</form>
	</div>
</div>

<script type="text/javascript">
	$(document).ready(function(){
		$("#orderFormAddForm").validate({
			rules : {
				customerName : {
					notNullCheck : true,
				},
				deliveryDate : {
					notNullCheck : true,
				},
				phoneNumber : {
					notNullCheck : true,
					isPhone : true,
				},
				address : {
					notNullCheck : true,
				},
			},
			messages : {
				customerName : {
					notNullCheck : '字段不能爲空',
				},
				deliveryDate : {
					notNullCheck : '字段不能爲空',
				},
				phoneNumber : {
					notNullCheck : '字段不能爲空',
					isPhone : "請輸入正確的手機號碼",
				},
				address : {
					notNullCheck : '字段不能爲空',
				},
			},
		})
		
		$("#orderFormAddSave").click(function(){
			if($("#orderFormAddForm").valid()) {
				$("#orderFormAddSave").attr("disabled", true);
				ajaxIss("orderFormController/saveOrderForm.do", $("#orderFormAddForm").serialize(), "FORM", function(data) {
					if(_oOrderFormDT != null) {
						_oOrderFormDT.draw();
					}
					layer.msg('訂單新增成功!');
					if(_layerIndex != null) {
						layer.close(_layerIndex);
					}
				}, function(data) {
					$("#orderFormAddSave").removeAttr("disabled");
					$("#orderFormAddSave").blur();
				});
			}
		});
		
		$("#orderFormAddClose").click(function() {
			if(_layerIndex != null) {
				layer.close(_layerIndex);
			}
		})
		
		$("#customerId_POP").select2({
	        placeholder: "選擇客戶",
	        minimumResultsForSearch: 2,
	        width : "100%",
	        allowClear:true,
	        language: "zh-CN",
	        ajax: {
	        	type: 'POST',
	            url: "customerInfoController/selectCustomerInfoBySearch.do",
	            dataType: 'json',
	            delay: 1000,
	            data: function (params) {
	                return {
	                	searchParam: encodeURI(params.term)
	                };
	            },
	            processResults: function (data) {
	                var itemList = [];//當數據對象不是{id:0,text:'ANTS'}這種形式的時候,可以使用類似此方法創建新的數組對象
	                if(data.object != null){
	                    _customerInfos = data.object;
	                    for(item in _customerInfos){
	                        itemList.push({id: item, text: _customerInfos[item].customerName});
	                    }
	                }
	                return {
	                	results: itemList,
	                };
	            },
	            cache: true
	        },  
	        minimumInputLength: 1,
	        maximumInputLength: 20,
	        minimumResultsForSearch: 1,
		}).change(function(){
			var customerInfo = _customerInfos[$("#customerId_POP option:selected").val()];
			if(typeof(customerInfo) != 'undefined' && customerInfo != null && customerInfo != ""){
				$("#phoneNumber_POP").val(customerInfo.phoneNumber);
				$("#address_POP").val(customerInfo.address);
			}
			else{
				$("#phoneNumber_POP").val("");
				$("#address_POP").val("");
			}
		});
		
		//日期框初始化
		$("._searchDate").datepicker({
			todayBtn: "linked",
			keyboardNavigation: false,
			forceParse: false,
			todayHighlight:true,
			autoclose: true,
		});
		
	})
</script>

後端代碼實現

1.controller方法

@RequestMapping("/selectCustomerInfoBySearch")
	public @ResponseBody JqueryResponse selectCustomerInfoBySearch(String searchParam){
		if(searchParam == null || searchParam.trim().equals(""))
			return new JqueryResponse();
		try {
			searchParam = URLDecoder.decode(searchParam,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return customerInfoService.selectCustomerInfoBySearch(searchParam);
	}

 2.impl方法

@Override
	public JqueryResponse selectCustomerInfoBySearch(String searchParam) {
		JqueryResponse jqueryResponse = new JqueryResponse();
		Map<String, CustomerInfo> customerInfoMap = CustomerInfoI.getInstance().getCustomerInfoBySearchForSelect2(searchParam);		
		jqueryResponse.setObject(customerInfoMap);
		return jqueryResponse;
	}

3.CustomerInfoI接口方法

package com.shyk.web.vca.cinterface;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.shyk.web.vca.dao.CustomerInfoMapper;
import com.shyk.web.vca.model.CustomerInfo;
import com.shyk.web.vca.utils.SpringTools;

public class CustomerInfoI {

	private static CustomerInfoI customerInfo;
	
	private static List<CustomerInfo> customerInfos;
	
	private static Map<String, CustomerInfo> customerInfoMaps;
	
	public static int needInit = 0;
	
	private CustomerInfoI() {
		init();
	}
	
	public Map<String, String> getCustomerInfos() {
		Map<String, String> _result = new LinkedHashMap<String, String>();
		
		if(customerInfos == null) {
			init();
		} else {
			for(CustomerInfo customerInfo : customerInfos) {
				_result.put(customerInfo.getId(), customerInfo.getCustomerName());
			}
		}
		return _result;
	}
	
	/**
	 * 查詢所有客戶名稱及Id,放入map中
	 */
	public Map<String, CustomerInfo> getCustomerInfoBySearchForSelect2(String searchParam) {
		Map<String, CustomerInfo> _map = new LinkedHashMap<String, CustomerInfo>();
		
		if(customerInfos != null && searchParam != null && !searchParam.trim().equals("")) {
			for(CustomerInfo customerInfo : customerInfos) {
				if(customerInfo.getCustomerName() != null && customerInfo.getCustomerName().indexOf(searchParam) >= 0) {
					_map.put(customerInfo.getId(), customerInfo);
				}
			}
		}
		return _map;
	}
	
	/**
	 * 根據ID,獲得客戶名稱,不存在則返回 null
	 */
	public String getNameById(String id) {
		String name = null;
		
		if(customerInfoMaps != null && id != null && !id.trim().equals("")) {
			if(customerInfoMaps.containsKey(id)) {
				name = customerInfoMaps.get(id) == null ? null : customerInfoMaps.get(id).getCustomerName();
			}
		}
		return name;
	}
	
	
	/**
	 * 數據初始化
	 */
	private void init() {
		CustomerInfoMapper mapper = (CustomerInfoMapper)SpringTools.getBean("customerInfoMapper");
		Map<String, Object> _map = new HashMap<String, Object>();
		_map.put("orderBy", "CreateTime ASC");
		customerInfos = mapper.selectCustomerInfos(_map);
		
		customerInfoMaps = new LinkedHashMap<String, CustomerInfo>();
		for(CustomerInfo customerInfo : customerInfos) {
			customerInfoMaps.put(customerInfo.getId(), customerInfo);
		}
		
		needInit = 0;
	}
	
	/**
	 * 單例模式
	 * @return
	 */
	public static synchronized CustomerInfoI getInstance() {
		if(customerInfo == null || needInit == 1) {
			customerInfo = new CustomerInfoI();
		}
		return customerInfo;
	}
}

 3、修改賦值通新增

 修改時前端頁面調用方法相同,但需要在進入修改頁面時默認給文本框賦值

可通過如下方法實現(供參考):

List查詢頁面代碼:

//點擊修改按鈕
	$("#orderFormModify").click(function() {
		if(_initPage == 0 || _oOrderFormSelectData == null || _oOrderFormSelectData['id'] == null) {
			return;
		}
		if(_oOrderFormSelectData['status'] != null && _oOrderFormSelectData['status'] != '正常') {
			layer.msg('只能修改狀態爲正常的信息!');
			return;
		}
		popURL("orderFormModifyLayer", "view/order/orderFormModify.html", "orderFormPop", "修改確認列表", "900px", "400px", function() {
			addSelectIss("customerId_POP", _dataExtend.customerInfos, true, "選擇客戶");
			loadDataIss("orderFormModifyForm", _oOrderFormSelectData);
		});
	});

 注意:addSelectIss()方法與loadDataIss()爲提前封裝好的方法

addSelectIss()——>

var addSelectIss = function(selectId, _map, isNull, nullText) {
	if($("#"+selectId).length > 0 ) {
		$("#"+selectId+" option").remove();
		if(isNull != null && isNull) {
			$("#"+selectId).append("<option value=''>"+nullText+"</option>");
		}
		for(var key in _map) {
			if (_map.hasOwnProperty(key)) {
				$("#"+selectId).append("<option value='"+key+"'>"+_map[key]+"</option>");
			}
		}
	}
}

loadDataIss()——>

var loadDataIss = function(formId, obj){
	var key,value,tagName,type,arr;
	for(x in obj){
		key = x;
		value = obj[x];
		$("#"+formId).find("[name='"+key+"'],[name='"+key+"[]']").each(function(){
			tagName = $(this)[0].tagName;
			type = $(this).attr('type');
			if(tagName=='INPUT'){
				if(type=='radio'){
					$(this).attr('checked',$(this).val()==value);
				}else if(type=='checkbox'){
					arr = value.split(',');
					for(var i=0;i<arr.length;i++){
						if($(this).val()==arr[i]){
							$(this).attr('checked',true);
							break;
						}
					}
				}else{
					$(this).val(value);
				}
			}else if(tagName=='SELECT' || tagName=='TEXTAREA'){
				$(this).val(value);
			}
			
		});
	}
}

僅需在修改的彈出框頁面加入以上兩個賦值方法即可實現修改賦值,重新選擇與新增彈出頁面相同。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章