简体   繁体   English

Select2设置多个选择的选项

[英]Select2 set multiple selected options

I've been searching for solutions to solve the follow problem, however previous questions I've read have yielded no successful results. 我一直在寻找解决以下问题的解决方案,但是我读过的先前的问题并未取得成功的结果。

I have a JSON encoded array stored in a database, for example ["2",2,5] . 我有一个存储在数据库中的JSON编码数组,例如["2",2,5] I need to cut the first value off the array and use the remaining items to select specific options in a multiple select from select2. 我需要从数组中删除第一个值,并使用其余项从select2的多选中选择特定选项。 My current solution show below displays the option corresponding to first value of the remaining array, but not the second. 我当前的解决方案如下所示,该选项显示与其余数组的第一个值相对应的选项,但不显示第二个值。 Any suggestions? 有什么建议么?

$("#sltETags").select2({ placeholder: 'Select a Primary Tag', minimumResultsForSearch: 8}).select2('val', [<?php $LstTags = json_decode($row["Tags"]); for($i = 1; $i < count($LstTags); $i++){ if($i != count($LstTags)-1){ echo '"'.$LstTags[$i].'",'; } else { echo '"'.$LstTags[$i].'"'; }} ?>]);

Outcome 结果

$("#sltETags").select2({ placeholder: 'Select a Primary Tag', minimumResultsForSearch: 8}).select2('val', ["2","5"]);

HTML Code HTML代码

<select class="form-control select2" multiple="multiple" data-placeholder="Select Secondary Tags" id="sltETags">
    <?php
    $LstTags = $TagManager->displayTags(0);
    for($i = 0; $i < count($LstTags); $i++){
        ?><option value="<?php echo $LstTags[$i][0]; ?>"><?php echo $LstTags[$i][1]; ?></option><?php
    } ?>
</select>

It seems the issue was the Javascript function to change the selected items. 似乎问题在于更改所选项目的Javascript函数。 My fix is below: 我的解决方法如下:

            <?php

                $LstTags = json_decode($row["Tags"]);

                for($i = 1; $i < count($LstTags); $i++){
                    $LstTags[$i] = "$LstTags[$i]";
                }

                $LstTags = json_encode($LstTags);

            ?>
            $("#sltETags").select2({ placeholder: 'Select a Primary Tag', minimumResultsForSearch: 8});
            $("#sltETags").val(<?php echo $LstTags; ?>).select2();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM