使用jQuery select2设置多个值

时间:2018-08-07 15:10:00

标签: javascript jquery html select jquery-select2

我使用jQuery select2选择多个列表项。

但是不幸的是,下面的代码必须将所有3个值都加载到选择字段中。但是,它仅加载第一项。

如何将所有3个项目加载到select2列表中?

<head>
<script  src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body>
    <select id="e1" style="width:400px">
        <option value="AL">Alabama</option>
        <option value="NY">New york</option>        
        <option value="WY">Wyoming</option>
    </select>
    <script>
    var selectedValuesTest = ["WY","AL", "NY"];
    $(document).ready(function() {
        $("#e1").select2({
                multiple: true,
            });
            $('#e1').select2('val', selectedValuesTest);
    });
    </script>    
</body>

1 个答案:

答案 0 :(得分:4)

select中设置值,并使用{p>触发change事件

$('#e1').val(selectedValuesTest).trigger('change');

var selectedValuesTest = ["WY", "AL", "NY"];
$(document).ready(function() {
  $("#e1").select2({
    multiple: true,
  });
  $('#e1').val(selectedValuesTest).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<select id="e1" style="width:400px" name="states[]">
  <option value="AL">Alabama</option>
  <option value="NY">New york</option>
  <option value="WY">Wyoming</option>
</select>