我有一个从数据库绑定的多选下拉列表,我想获取所选值的ID
我尝试使用jquery函数来获取所选值的数组,但它永远无法正常工作
我的html代码
@Html.DropDownListFor(x => x.RolesMenusMain, GlobalLists.GetMenus(),
new { @class = "form-control select2 multiple", multiple = "multiple", selectedvalue = selected })
jquery代码
$(document).ready(function () {
$('.select2').select2({
width: '100%'
});
debugger;
var IDs = [];
for (var i = 0; i < $("#RolesMenusMain").attr("selectedvalue").split(",").length; i++) {
if ($("#RolesMenusMain").attr("selectedvalue").split(",")[i] != "")
IDs.push($("#RolesMenusMain").attr("selectedvalue").split(",")[i]);
alert(IDs);
}
$("#RolesMenusMain").val(IDs).trigger("change");
});
答案 0 :(得分:0)
使用伪选择器:selected
获取所选选项。
$('select').on('change', function() {
const selectedOption = $('select option:selected')[0];
console.log(selectedOption);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="garden">
<option>Flowers</option>
<option>Shrubs</option>
<option>Trees</option>
<option>Bushes</option>
<option>Grass</option>
<option>Dirt</option>
</select>
答案 1 :(得分:0)
您的代码正常,并可以按照以下代码片段所示工作。确保变量selected
是一个字符串,其中包含用逗号分隔的ID。
$(document).ready(function () {
$('.select2').select2({
width: '100%'
});
debugger;
var IDs = [];
for (var i = 0; i < $("#RolesMenusMain").attr("selectedvalue").split(",").length; i++) {
if ($("#RolesMenusMain").attr("selectedvalue").split(",")[i] != "")
IDs.push($("#RolesMenusMain").attr("selectedvalue").split(",")[i]);
alert(IDs);
}
$("#RolesMenusMain").val(IDs).trigger("change");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>
<select id="RolesMenusMain" multiple="multiple" class="select2" selectedvalue="1,2,3">
<option value="">---</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>