从 jquery 中的数据库中获取多选下拉列表绑定的选定 ID 值

get selected id value of multiselect dropdown binds from database in jquery

我有一个从数据库绑定的多 select 下拉列表我想获取 selected 值的 ID

我尝试使用 jquery 函数来获取 selected 值的数组,但它永远不起作用

我的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");
    });

使用伪选择器: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>

您的代码没有问题,应该会如以下代码片段所示那样工作。确保变量 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>