在使用select2插件时,我们经常用到输入的值没有匹配到,想要把当前输入的值放到下拉框,这里我举例两种不同的写法,基于angularJS和javaScript.
// html页面代码
<div class="col-md-4">
<div class="form-group">
<label class="col-md-5 control-label">单位名称:<span class="required" style="color:red">*</span></label>
<div class="col-md-7">
<input type="hidden" id="visitUnit" ng-model="tbTcTouristComplaints.visitUnit"
class="form-control select2" style="height: 29px !important;padding: 1px 10px 3px 10px !important;">
</div>
</div>
</div>
对比jsp代码:
// jsp页面代码
<div class="col-md-4">
<div class="col-md-4">
<div class="form-group">
<label class="col-md-5 control-label">单位名称:<span class="required" style="color:red">*</span></label>
<div class="col-md-7">
<input type="hidden" id="visitUnit" name="receptionApply.visitUnit" class="form-control input-sm select2">
</div>
</div>
</div>
$scope._initSelect2 = function(formId,scope) {
var obj = $("#visitUnit").select2({
placeholder: "请输入单位名称",
allowClear: true,
minimumInputLength: 1,
formatNoMatches: function () { return "没有找到匹配项"; },
formatInputTooShort: function (input, min) { var n = min - input.length; return "请再输入" + n + "个字符";},
formatInputTooLong: function (input, max) { var n = input.length - max; return "请删掉" + n + "个字符";},
formatSelectionTooBig: function (limit) { return "你只能选择最多" + limit + "项"; },
formatLoadMore: function (pageNumber) { return "加载结果中…"; },
formatSearching: function () { return "搜索中…"; },
query: function (query) {
if(query.term==null ||query.term.trim()=='')
return;
//如下这段代码是angularJS从后台调用方法获取数据,({name:query.term}是传入的输入的值。类似于ajax请求。
complaintMangeService.tbComplaintsTest({name:query.term}).then(function(data){
console.log(data);//从后台得到匹配到的值
var datas = {
results: []
}, i, j, s;
if (data.length > 0) {//先将当前输入的值封装到datas.results
if(query.term != data[0].NAME){
datas.results.push({
id: query.term,
text: query.term
});
}
for (i = 0; i < data.length; i++) {//然后将后台得到匹配到的值封装datas.results
s = "";
datas.results.push({
id: data[i].NAME,
text: data[i].NAME
});
}
query.callback(datas);
}else{//如果后台没有匹配到的值,则将当前输入的值封装到datas.results
datas.results.push({
id: query.term,
text: query.term
});
query.callback(datas);//回调query函数
}
},function(data){
console.log("(系统参数查询)其他企业wid查询数据请求失败!")
});
}
});
//obj.on("change",function()方法是当选中值以后需要做什么操作可在这里面写,
/* obj.on("change",function(){
var sUnitName = $('#visitUnit').val();
if(sUnitName==null ||sUnitName.trim()==''){
if(document.getElementById('visitUnitType').disabled){
$('#visitUnitContact').val('');
$('#contactTele').val('');
$('#visitUnitType').val('');
$('#visitUnitLevel').val('');
$('#visitUnitType').removeAttr("disabled");
$('#visitUnitLevel').removeAttr("disabled");
return;
}else{
$('#visitUnitType').removeAttr("disabled");
$('#visitUnitLevel').removeAttr("disabled");
return;
}
};
$.ajax({
"dataType": 'json',
"type": "POST",
"data":{"params.visitUnit":sUnitName},
"url": scope._serverUrl+"reception/common_queryApplyByVisitUnit",
"success":function (result) {
if(result.params.returnApply !=null ){
$('#visitUnitContact').val(result.params.returnApply.visitUnitContact);
$('#contactTele').val(result.params.returnApply.contactTele);
$('#visitUnitType').val(result.params.returnApply.visitUnitType);
$('#visitUnitLevel').val(result.params.returnApply.visitUnitLevel);
$('#visitUnitType').attr("disabled","disabled");
$('#visitUnitLevel').attr("disabled","disabled");
if(result.params.returnApply.majorGuest!=null){
$('#majorGuest').importTags(result.params.returnApply.majorGuest);
$('#'+formId).validate().element( "#majorGuest" );
}
if(result.params.returnApply.higherAccompanyLeader != null){
$('#higherAccompanyLeader').importTags(result.params.returnApply.higherAccompanyLeader);
$('#'+formId).validate().element( "#higherAccompanyLeader" );
}
$('#'+formId).validate().element( "#visitUnitType" );
$('#'+formId).validate().element( "#visitUnitLevel" );
$('#'+formId).validate().element( "#visitUnitContact" );
$('#'+formId).validate().element( "#contactTele" );
}else{
$('#visitUnitType').removeAttr("disabled");
$('#visitUnitLevel').removeAttr("disabled");
}
}, error: function(XMLHttpRequest, textStatus, errorThrown){
bootbox.alert("连接到服务器出现错误,请稍后再试。");
}
});*/
}
);
};
//初始化控件,一定要初始化才能用,对于angularJS,("modofficialOrderForm","")这两个参数可不传,因为完全没啥用,可以直接写成$scope._initSelect2();
$scope._initSelect2("modofficialOrderForm","");
对于jsp/javascript框架,写法如下(写法和angularJS相同,只是初始化不同和获取后台的数据是采用ajax请求):
this._initSelect2 = function(formId,scope) {
if($("#visitUnitType").val() != ""){
$('#visitUnitType').attr("disabled","disabled");
}
if($("#visitUnitLevel").val() != ""){
$('#visitUnitLevel').attr("disabled","disabled");
}
var obj = $("#visitUnit").select2({
placeholder: "请输入单位名称",
allowClear: true,
minimumInputLength: 1,
formatNoMatches: function () { return "没有找到匹配项"; },
formatInputTooShort: function (input, min) { var n = min - input.length; return "请再输入" + n + "个字符";},
formatInputTooLong: function (input, max) { var n = input.length - max; return "请删掉" + n + "个字符";},
formatSelectionTooBig: function (limit) { return "你只能选择最多" + limit + "项"; },
formatLoadMore: function (pageNumber) { return "加载结果中…"; },
formatSearching: function () { return "搜索中…"; },
query: function (query) {
if(query.term==null ||query.term.trim()=='')
return;
$.ajax({
"dataType": 'json',
"type": "POST",
"data": "¶ms.paramer=" + query.term + "¶ms.type=" + $('#visitUnitType').val(),
"url": scope._serverUrl+"reception/common_queryVisitTypeName",
"success":function (result) {
var datas = {
results: []
}, i, j, s;
if (result.params.visitTypeName.length > 0) {
if(query.term != result.params.visitTypeName[0].MANAGE_VISIT_UNIT){
datas.results.push({
id: query.term,
text: query.term
});
}
for (i = 0; i < result.params.visitTypeName.length; i++) {
s = "";
datas.results.push({
id: result.params.visitTypeName[i].MANAGE_VISIT_UNIT,
text: result.params.visitTypeName[i].MANAGE_VISIT_UNIT
});
}
query.callback(datas);
}else{
datas.results.push({
id: query.term,
text: query.term
});
query.callback(datas);
}
}, error: function(XMLHttpRequest, textStatus, errorThrown){
bootbox.alert("连接到服务器出现错误,请稍后再试。");
}
});
}
});
/* obj.on("change",function(){
var sUnitName = $('#visitUnit').val();
if(sUnitName==null ||sUnitName.trim()==''){
if(document.getElementById('visitUnitType').disabled){
$('#visitUnitContact').val('');
$('#contactTele').val('');
$('#visitUnitType').val('');
$('#visitUnitLevel').val('');
$('#visitUnitType').removeAttr("disabled");
$('#visitUnitLevel').removeAttr("disabled");
return;
}else{
$('#visitUnitType').removeAttr("disabled");
$('#visitUnitLevel').removeAttr("disabled");
return;
}
};
$.ajax({
"dataType": 'json',
"type": "POST",
"data":{"params.visitUnit":sUnitName},
"url": scope._serverUrl+"reception/common_queryApplyByVisitUnit",
"success":function (result) {
if(result.params.returnApply !=null ){
$('#visitUnitContact').val(result.params.returnApply.visitUnitContact);
$('#contactTele').val(result.params.returnApply.contactTele);
$('#visitUnitType').val(result.params.returnApply.visitUnitType);
$('#visitUnitLevel').val(result.params.returnApply.visitUnitLevel);
$('#visitUnitType').attr("disabled","disabled");
$('#visitUnitLevel').attr("disabled","disabled");
if(result.params.returnApply.majorGuest!=null){
$('#majorGuest').importTags(result.params.returnApply.majorGuest);
$('#'+formId).validate().element( "#majorGuest" );
}
if(result.params.returnApply.higherAccompanyLeader != null){
$('#higherAccompanyLeader').importTags(result.params.returnApply.higherAccompanyLeader);
$('#'+formId).validate().element( "#higherAccompanyLeader" );
}
$('#'+formId).validate().element( "#visitUnitType" );
$('#'+formId).validate().element( "#visitUnitLevel" );
$('#'+formId).validate().element( "#visitUnitContact" );
$('#'+formId).validate().element( "#contactTele" );
}else{
$('#visitUnitType').removeAttr("disabled");
$('#visitUnitLevel').removeAttr("disabled");
}
}, error: function(XMLHttpRequest, textStatus, errorThrown){
bootbox.alert("连接到服务器出现错误,请稍后再试。");
}
});
}*/
);};
//初始化控件,一定要初始化才能用,fromId是页面上form表单的id,scope是请求地址路径
this._init = function(fromId, scope, useIframe, serverUrl){
this._initSelect2(fromId,scope);
};
//如下的js和css文件可以再网上随便下载一个都能用,或者直接使用bootstrap框架里面的也可以的
<link rel="stylesheet" href="plugins/select2/select2.css">
<script src="plugins/select2/js/i18n/zh-CN.js" type="text/javascript"></script>
<script src="plugins/select2/select2.js" type="text/javascript"></script>
<script src="plugins/select2/select2.min.js" type="text/javascript"></script>
(2)输入一个后台能匹配到的值,执行结果(当前下拉匹配到值):
(2)当输入一个后台没有匹配到的值时,就会将当前值放入到下拉框作为新值选项赋值给文本框:
(3)可直接通过id获取到下拉框的值,然后执行保存数据操作:
$("#visitUnit").val();