简体   繁体   English

如何使用codeigniter中的数据库数据在Select2中设置值

[英]How to set value in Select2 using database data in codeigniter

I really need help on my problem, i am trying to set a value in my select2 using the data that i had fetch in my database using ajax.我真的需要关于我的问题的帮助,我正在尝试使用我使用 ajax 在我的数据库中获取的数据在我的 select2 中设置一个值。

here is my view in select2这是我在 select2 中的视图

  <select multiple id="multiple_assigned" style="width:300px">
          <option value="1">Test1</option>
          <option value="2">Test2</option>
          <option value="3">Test3</option>
          <option value="4">Test4</option>
          <option value="5">Test5</option>
          <option value="6">Test6</option>
          <option value="7">Test7</option>
          <option value="8">Test8</option>
      </select>

the data is look like this:数据是这样的:

0: {users_id: "1"}
1: {users_id: "2"}
2: {users_id: "3"}
3: {users_id: "4"}
4: {users_id: "5"}
5: {users_id: "6"}

here is my ajax looks like:这是我的 ajax 看起来像:

        $.ajax({
            url: url,
            type: "GET",
            dataType: "JSON",
            data: $('#form').serialize(),
            success: function(data) {

                for(i=0; i<data.length; i++){
                  $('#multiple_assigned').val(data[i]);
                }

            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert('Error adding / update data');
            }
        });

thank you in advance.先感谢您。 i just need to show all the data that i had fetch through my database in the select2.我只需要在 select2 中显示我通过我的数据库获取的所有数据。 any answer will be really appreciated thanks.任何答案将不胜感激,谢谢。

    #use css/select2.min.css
    #use js/select2.full.min.js
    # then add class="select2"
    #Example:
    <select class="select2" multiple>
              <option value="1">Test1</option>
              <option value="2">Test2</option>
              <option value="3">Test3</option>
              <option value="4">Test4</option>
              <option value="5">Test5</option>
              <option value="6">Test6</option>
              <option value="7">Test7</option>
              <option value="8">Test8</option>
    </select>
#then use this script
<script>
    $(function() {
        //Initialize Select2 Elements
        $('.select2').select2()

    })
</script>

i already got the answer.我已经得到了答案。

            success: function(data) {
                //if success close modal and reload ajax table
                var selectedValues = new Array();
                for(i=0; i<data.length; i++){
                    selectedValues[i] =   data[i]['users_id']
                    $('#multiple_assigned').val(selectedValues);
                    }
                $("#multiple_assigned").select2();

            },

i just need to declare an array, then loop through it.我只需要声明一个数组,然后循环遍历它。

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

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