简体   繁体   English

使用 json_encode 在 js 中初始化的 php 数组数据填充 id/text select2

[英]Populate id/text select2 with php's array data initialized in js with json_encode

i was just introduced to select2, and in order to populate it i'm trying to use a php array and json encode it, but the results now is only showing the dropdown results as value=option text, i want to show the text and use the corresponding value for other operations, snaps of my code :我刚刚被介绍到 select2,为了填充它,我正在尝试使用 php 数组和 json 对其进行编码,但现在结果只将下拉结果显示为 value=option 文本,我想显示文本和将相应的值用于其他操作,我的代码快照:

  $sqlGetUserList="My query here";
    $resultGetUserList = $conn->query($sqlGetUserList);

    <div id="cid_11" class="form-input-wide">      
       <select class="js-user-basic-single"  id="user"  name="user" required onchange="getUserPlan();" style="width:250px;" data-component="dropdown">
        <option value=''></option>
     <?php while ($rowGetUserList= mysqli_fetch_array($resultGetUserList)) {  
      $arr[]=$rowGetUserList['user_Id']; 
}  ?>
</select>

Now i retrieved the id that i want to set as the value="" of the option现在我检索了我想设置为该选项的 value="" 的 id

My JS :我的JS:

 var tempArrayID = <?php echo json_encode($arr); ?>;
$(".js-user-basic-single").select2({
  data: tempArrayID
})

Is there a way i can tell select2 that the value needed should be retrieved from the ID array, and the text is to be retrieved from a second array where i retrieve the string ?有什么方法可以告诉 select2 所需的值应该从 ID 数组中检索,而文本将从我检索字符串的第二个数组中检索?

I've used Jquery UI autocomplete/combobox instead, and it is perfectly working for my current needs!我改用了 Jquery UI 自动完成/组合框,它非常适合我当前的需求! For more info : https://jqueryui.com/autocomplete/#combobox][1]欲了解更多信息: https : //jqueryui.com/autocomplete/#combobox][1]

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

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