jQuery判断多选下拉列表选中状态及全取消时提示的实现方法
实现方案
核心改动点
- 移除原有函数中冗余的嵌套遍历逻辑(map内部套each属于重复遍历,无实际作用)
- 生成选中项数组后新增长度判断,长度为0时直接输出控制台提示
- 其余原有逻辑(生成JSON、编码URI)保持不变
完整修改后代码
JS部分
function getSelects() { $('#selectedText').val(''); // 生成选中项数组 var items = $("#Customers > option:selected").map(function () { // 可按业务需求补充opt对象的属性,此处为示例 return { customerId: $(this).val(), customerName: $(this).text() }; }).get(); // 新增判断:所有选项都被移除时输出提示 if (items.length === 0) { console.log('多选下拉列表的所有已选选项已全部移除'); return; } // 原有逻辑:编码为URI组件 const encodedValue = encodeURIComponent(JSON.stringify(items)); $('#selectedText').val(encodedValue); console.log('当前选中项编码结果:', encodedValue); }
HTML部分(无需修改,保持原有事件绑定即可)
<div class="form-group row"> <label class="col-sm-3 col-form-label">Customer</label> <div class="col-sm-9"> <select id="Customers" class="js-select2-custom custom-select" name="CustomerID" multiple size="1" style="opacity: 0;" asp-for="CustomerID" onchange="getSelects()" data-hs-select2-options='{ "minimumResultsForSearch": "Infinity" }'> @{ var selectedCustomer = Model.CustomerList.Where(x => Model.SelectedCustomers.Any(c => c.CustomerID == x.CustomerID)); var Customers = Model.CustomerList.Where(x => !Model.SelectedCustomers.Any(c => c.CustomerID == x.CustomerID)); } @foreach (var item in selectedCustomer) { <option value="@item.CustomerID" selected>@item.CustomerName</option> } @foreach (var item in Customers) { <option value="@item.CustomerID">@item.CustomerName</option> } </select> </div> </div>
逻辑说明
当用户清空所有选中项时,$("#Customers > option:selected")选择器匹配到的元素数量为0,生成的items数组长度为0,触发判断逻辑后直接输出对应控制台提示,终止后续不必要的编码操作。
内容的提问来源于stack exchange,提问作者Anton Marcus
相关产品推荐
相关产品推荐

