select2 - 单击时未选择下拉选项
Posted
技术标签:
【中文标题】select2 - 单击时未选择下拉选项【英文标题】:select2 - dropdown options don't get selected on click 【发布时间】:2021-09-16 00:49:11 【问题描述】:我有这个 Razor 下拉菜单,它通过 ajax 从数据库中获取信息,但没有选择下拉菜单中显示的选项。如何使下拉选项在点击时被选中?
我尝试实现类似问题的答案,但没有奏效:
select2 load data using ajax cannot select any option
这是我目前所拥有的:
阿贾克斯
$(document).ready(function ()
$.validator.addMethod("regxPhone", function (value, element, regexpr)
return regexpr.test(value);
),
$.validator.addMethod("regxEmail", function (value)
return /^([\w!.%+\-])+@@([\w\-])+(?:\.[\w\-]+)+$/.test(value);
),
$.validator.addMethod('validEmail', function (value, element, param)
return valiEmailAjax($("#Email").val());
);
$('#dropdown-employees').select2(
minimumInputLength: 0,
multiple: false,
dropdownParent: $('#dropdown-email-for-select2'),
ajax:
url: "/en/BOEmployeeAjax/GetEmployeesExcept",
type: "POST",
dataType: "json",
data: function (params)
return
emplId: 0,
t: params.term
,
processResults: function (data, params)
return results: data
,
placeholder: window.selectAnotherSupervisor,
escapeMarkup: function (markup) return markup; ,
);
剃刀下拉菜单
<div class="col-md-4 fieldSize4" id="dropdown-employees">
@html.DropDownListFor(x => x.Employee, new SelectList(new Dictionary<string, string>(), "Key", "Value"), @FXM.BO.Strings.T("ddl_select_option"), new @class = "form-control select2-allow-clear", @placeholder = "Select Symbols" )
<span class="help-block">
@FXM.BO.Strings.T("lbl_employee_description")
</span>
</div>
第一次更改后的代码:
@model FXM.BO.ViewModels.NewAffiliateViewModel
@
ViewBag.Title = "CreateAffiliate";
Layout = "~/Views/Shared/_LoggedInLayout.cshtml";
<h2>Create Affiliate</h2>
@using (Html.BeginForm())
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4 class="hidden">NewAffiliateViewModel</h4>
<hr />
@Html.ValidationSummary(true, "", new @class = "text-danger" )
<div class="form-group">
@Html.LabelFor(model => model.AffiliateName, htmlAttributes: new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model.AffiliateName, new htmlAttributes = new @class = "form-control" )
@Html.ValidationMessageFor(model => model.AffiliateName, "", new @class = "text-danger" )
</div>
</div>
<div class="form-group" id="dropdown-email-for-select2">
@Html.LabelFor(model => model.Email, htmlAttributes: new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new htmlAttributes = new @class = "form-control" )
@Html.ValidationMessageFor(model => model.Email, "", new @class = "text-danger" )
</div>
</div>
@*<div class="form-group">
@Html.LabelFor(model => model.Employee, htmlAttributes: new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model.Employee, new htmlAttributes = new @class = "form-control" )
@Html.ValidationMessageFor(model => model.Employee, "", new @class = "text-danger" )
</div>
</div>*@
@*<div class="form-group">
@Html.LabelFor(model => model.MT4Group, htmlAttributes: new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model.MT4Group, new htmlAttributes = new @class = "form-control" )
@Html.ValidationMessageFor(model => model.MT4Group, "", new @class = "text-danger" )
</div>
</div>*@
<div class="form-group">
<label class="control-label col-md-2">
@FXM.BO.Strings.T("employeeName") <span class="required">
@***@
</span>
</label>
@*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*@
<div class="col-md-4 fieldSize4" id="dropdown-employees">
@Html.DropDownListFor(x => x.Employee, new SelectList(new Dictionary<string, string>(), "Key", "Value"), @FXM.BO.Strings.T("ddl_select_option"), new @class = "form-control select2-allow-clear", @placeholder = "Select Symbols" )
<span class="help-block">
@FXM.BO.Strings.T("lbl_employee_description")
</span>
</div>
@*<img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />*@
</div>
<div class="form-group">
<label class="control-label col-md-2">
@FXM.BO.Strings.T("lbl_Bo_TradAcc_PlatformGroup") <span class="required">
@***@
</span>
</label>
@*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*@
<div class="col-md-4 fieldSize4">
@Html.DropDownListFor(x => x.MT4Group, new SelectList(new Dictionary<string, string>(), "Key", "Value"), @FXM.BO.Strings.T("ddl_select_option2"), new @class = "form-control select2-allow-clear", @placeholder = "Select Symbols" )
<span class="help-block">
@FXM.BO.Strings.T("platform_group_description")
</span>
</div>
<img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />
</div>
@*Create button*@
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Create" class="btn btn-default" id="create-affiliate-button" />
</div>
</div>
</div>
@*<div>
@Html.ActionLink("Back to List", "Index")
</div>*@
<script type="text/javascript" src="/Scripts/CustomScripts/Common/form-helpers.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
// document.ready function
$(function ()
refreshGroups();
// selector has to be . for a class name and # for an ID
$('#create-affiliate-button').click(function (e)
//e.preventDefault(); // prevent form from reloading page
console.log("blahblahblah");
//alert("hiii");
var b = $("form").serialize();
//var a = $("form").serializeArray();
console.log("formvalues", b);
$.ajax(
url: "@Url.Action("CreateAffiliate", "AjaxUI")",
type: "GET",
dataType: "json",
data:
newAffiliateViewModel : b
,
//error: function (jqXHR, exception)
// failMessage();
//
);
);
);
function refreshGroups()
var pltf = "MT4_LIVE";
var out = $('#MT4Group');
if (pltf != null && pltf !== "")
$.ajax(
url: '/' + window.currentLangCulture + '/BOLiveForms/GetPlatformGroupByFilter',
data:
platform: pltf, currency: "", withId : true
,
type: 'GET',
beforeSend: function ()
$('#tpLoader').show();
,
complete: function ()
$('#tpLoader').hide();
,
success: function (data)
populateDropDown(out, data);
//$('#recomandedGroup').show();
);
else
out.empty();
out.append($('<option></option>').val('').html(window.defaultSelection));
//GetEmployeesExcept - Method that populates the Dropdown for EmployeeName
$(document).ready(function ()
$.validator.addMethod("regxPhone", function (value, element, regexpr)
return regexpr.test(value);
),
$.validator.addMethod("regxEmail", function (value)
return /^([\w!.%+\-])+@@([\w\-])+(?:\.[\w\-]+)+$/.test(value);
),
$.validator.addMethod('validEmail', function (value, element, param)
return valiEmailAjax($("#Email").val());
);
var WithId = $('#dropdown-employees');
if(WithId.length>0)
var ajax_url = '/en/BOEmployeeAjax/GetEmployeesExcept';
var $ajax = WithId;
loadSelectData();
);
function loadSelectData()
var cstoken = $('input[name="_token"]').val();
$ajax.select2(
ajax:
url: ajax_url,
dataType: 'json',
data: function (params, cstoken, page)
return
"_token": cstoken,
searchtxt: params.term, // search term
page: params.page
;
,
processResults: function (data)
var vh = [];
var obj = jQuery.parseJSON(data);
$.each(obj, function(key,value)
var itemName = value.empname;
var itemId = value.id;
vh.push(id: itemId, text: itemName );
);
console.log(vh);
return
results: vh,
pagination:
more: true
,
placeholder: 'Search for a result',
minimumInputLength: 1,
);
</script>
【问题讨论】:
【参考方案1】:请更改您的 select2 ajax 代码。
Please change your select2 ajax code like.
$(document).ready(function ()
$.validator.addMethod("regxPhone", function (value, element, regexpr)
return regexpr.test(value);
),
$.validator.addMethod("regxEmail", function (value)
return /^([\w!.%+\-])+@@([\w\-])+(?:\.[\w\-]+)+$/.test(value);
),
$.validator.addMethod('validEmail', function (value, element, param)
return valiEmailAjax($("#Email").val());
);
var WithId = $('#dropdown-employees');
if(WithId.length>0)
var ajax_url = '/en/BOEmployeeAjax/GetEmployeesExcept';
var $ajax = WithId;
loadSelectData();
);
function loadSelectData()
var cstoken = $('input[name="_token"]').val();
$ajax.select2(
ajax:
url: ajax_url,
dataType: 'json',
data: function (params, cstoken, page)
return
"_token": cstoken,
searchtxt: params.term, // search term
page: params.page
;
,
processResults: function (data)
var vh = [];
var obj = jQuery.parseJSON(data);
$.each(obj, function(key,value)
var itemName = value.empname;
var itemId = value.id;
vh.push(id: itemId, text: itemName );
);
console.log(vh);
return
results: vh,
pagination:
more: true
,
placeholder: 'Search for a result',
minimumInputLength: 1,
);
【讨论】:
感谢您的意见,谢谢。您的代码修复了下拉列表的大小 - 现在它具有相同的大小并且看起来与页面中的其他下拉列表相同,这很棒。问题是下拉列表不再从数据库接收数据。当我单击它时,它不会填充可供选择的选项。当然,我不能选择任何东西来查看它是否被选中。以上是关于select2 - 单击时未选择下拉选项的主要内容,如果未能解决你的问题,请参考以下文章
使用 select2 4.0.3 创建下拉数组并禁用基于其他 select2 值的选项