2017-04-03 204 views
0

我一直在尋找解決方案來解決以下問題,但是我讀過的以前的問題沒有取得任何成功的結果。Select2設置多個選定的選項

我有一個JSON編碼數組存儲在數據庫中,例如["2",2,5]。我需要從陣列中刪除第一個值,並使用其餘項目從select2中選擇多個特定選項。我目前的解決方案顯示如下顯示的選項對應的剩餘數組的第一個值,但不是第二個。有什麼建議麼?

$("#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].'"'; }} ?>]); 

成果

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

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> 

回答

0

看來問題是JavaScript函數來更改所選項目。我的修復程序如下:

  <?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();