编辑表单时如何显示从数据库中选择的值?

How to show selected values from database when edit the form?

我正在为我的字段之一使用 Select2。数据完美地插入到数据库中。但是当我想编辑表单时,我需要从数据库中获取数据。我可以获取数据,但我不知道如何在编辑表单时在 Select2 中显示值。 这是我在数据库中插入数据时的代码。 table 名称是 "requests",存储数组的列是 "crimes_section"。

 <div class="form-group">
   <label>Crime Section / جرم</label>
     <select class="crimeSections form-control" name="crimeSection[]" multiple="multiple" style="border-radius: 0px;" placeholder="35201-4578979-0">
         <option value="AL">Alabama</option>
         <option value="WY">Wyoming</option>
      </select>
  </div>
<script type="text/javascript">
$(document).ready(function() {
   $('.crimeSections').select2({
   placeholder: "381, 392, 420"
   });
});
</script>

假设下面是从数据库接收到的数据。

var data = [
    {
        id: 0,
        text: 'enhancement'
    },
    {
        id: 1,
        text: 'bug'
    },
    {
        id: 2,
        text: 'duplicate'
    },
    {
        id: 3,
        text: 'invalid'
    },
    {
        id: 4,
        text: 'wontfix'
    }
];

这是将数据填充到 select 框中的方法之一,通过触发更改事件,您可以设置默认值。

$('#example').select2({
    data: data
}).val(1).trigger('change'); //This will set bug as selected value

您可以同时使用这两个选项。使用隐藏字段设置要从数据库设置的值

$('#sel_users').val(value);
$('#sel_users').select2().trigger('change');

尝试

Array.from(document.querySelector('.crimeSections').options).forEach(option=>{
if(option.value=="AL")
option.selected=true
});

编辑:将 "AL" 替换为您要匹配的值

这段代码适合我。

$(document).ready(function() {
    $('#selectedCrimes').select2({
    multiple: true,
    });
});

感谢大家。