Populate multi-selection field with jquery and php

  javascript, jquery, php

I think this is simple one but I am not getting this for sometimes now. I was ready many answers and I am not able to find exact answer for my problem.
Below is the problem I am getting.

When i click on edit on a record it will send a ajax request to fetch the record data and populate the data to form with jquery as below. the issue is when i want to populate the values for multi-select field, below is my code.

My Model

public function get_single_item($id)
{
    $this->db->select('*');
    $this->db->from('items');
    $this->db->where('id', $id);

    return $this->db->get()->result();
}

My Controller

public function get()
{
    $this->load->model('admin/items_model', 'mim');

    $id = $this->input->post('id');
    $data =$this->mim->get_single_item($id);
    
    echo json_encode($data);
}

Javascript Code to populate values

    $('.edit').click(function(){

  var id = $(this).attr('id');

  $.ajax({
    url: "<?= base_url('items/get') ?>",
    method: "POST",
    data:{id:id},
    dataType: "json",
    success:function(data)
    {
      $('.item_modal').modal('show');
      $('#item_name').val(data[0].item_name);
      $('#condiments').val(data[0].condiments);
      $('#others').val(data[0].others); //this is the multi-select field
      $('#price').val(data[0].item_price);
      $('#location').val(data[0].location);

    }

  });});

Records
When I select a record has two values it shows nothing is selected as below.

Does not select any values

But if i select a record which has only one value it selects as below.

Selects only one value

Much appreciated if anyone could help me with this please.

Source: Ask PHP

LEAVE A COMMENT