无法将数据附加到select2选项

时间:2019-10-28 08:05:50

标签: php jquery codeigniter jquery-select2

我想制作编辑表单并将数据库中的数据附加到select2选项。当我们逐字键入时,该select2选项以插入形式在数据库中搜索数据。我无法在此select2选项中附加数据。我想使这个select2选项充满数据库中的数据,并且还可以像插入表格一样更改数据。我已经尝试过$('#requestor')。val($ row ['requestor']);但没有出现数据。谁能帮我吗?

 <select class="requestor form-control" name="requestor" id="requestor" style="width:700px"  required="required">
 <option value=""></option>
 </select>

 //search data in database word by word
 $('.requestor').select2({
            placeholder: 'Requestor Name',
            ajax:{
                url: "<?php echo base_url('Hire_4/select_personnel'); ?>",
                dataType: "json",
                delay: 250,
                processResults: function(data){
                    var results = [];

                    $.each(data, function(index, item){
                        results.push({
                            id: item.ID,
                            text: item.FullName,
                            option_value:item.ID
                        });     
                    });

                    return{
                        results: results,
                        cache: true,
                    };
                },
            }
        });
 function load() {
alert('ok');
//console.log(<?php echo $row['ID']; ?>);

if (<?php echo $row['ID']; ?> != '') {
  $('#requestor').val($row['requestor']);
}
}

window.onload = load;

谢谢:)

1 个答案:

答案 0 :(得分:0)

您的代码非常混乱。像这样更清楚:

<div class="col-md-12">
  <select style="width:100%;" name="requestor[]" id="requestor" class="select2-multiple" multiple></select> 
</div>  

然后:

var $ajax = $("#requestor");

$ajax.select2({
   ajax: {
        url: "<?php echo base_url('Hire_4/select_personnel'); ?>",
        type: "post",
        dataType: 'json',
        delay: 250,
        data: function (params) {
        return{             
           search: params.term
        };
   },
   processResults: function (data, params) {
   params.page = params.page || 1;
   return {
      results: data
   };
   },
   cache: true
   },
   language: "en",
   placeholder: "Requestor Name",
   allowClear: true,
   minimumInputLength: 3,
   maximumSelectionLength: 1,
   escapeMarkup: function (markup) { return markup; },
   templateResult: formatRepo,
   templateSelection: formatRepoSelection
});

function formatRepo(repo) {
   var markup = repo.text ;
   return markup;
}

function formatRepoSelection (repo) {
   return repo.Name.replace(/<\/?("[^"]*"|'[^']*'|[^>])*(>|$)/g, "");
}

您的Ajax数据必须具有以下格式:

data[0]['ID'] = 1; //You must have "ID" key
data[0]['Name'] = 'Name'; //You must have "Name" key

就这么简单! 祝你好运。