skip to Main Content

is there any way to make select2 auto select an item on ajax request when an specific condition matches?

The below is my current code:

 const optionFormatSelect = (item) => {
    if (!item.id) {
        return item.text;
    }

    var span = document.createElement('span');
    var template = '';

    template += '<div class="d-flex align-items-center">';
    template += '<div class="d-flex flex-column">'
    template += '<span class="fs-6 fw-bold lh-1">' + item.name + '</span>';
    
    // Access the data attributes directly from item
    if (item.email) {
        template += '<span class="text-dark fs-7 owner-email">' + item.email + '</span>';
    }
    
    if (item.phone) {
        template += '<span class="text-dark fs-7 owner-phone">' + item.phone + '</span>';
    }

    template += '</div>';
    template += '</div>';

    span.innerHTML = template;

    return $(span);
}


function populateOwnerSelect(owner_id = null) {
    var ownerSelect = $('#owner_id');
    ownerSelect.empty();
    ownerSelect.select2({
        placeholder: "Select an owner",
        dropdownParent: $("#editModal"),
        ajax: {
            url: '{{ route('owners.getList') }}',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                if (owner_id !== null && params.term === undefined) {
                    return {
                        id: owner_id,
                    };
                } else {
                    return {
                        q: params.term,
                    };
                }
            },
            processResults: function (data, params) {
                return {
                    results: data.results,
                };
            },

            cache: true
        },
        escapeMarkup: function(markup) {
            return markup;
        },
        templateSelection: optionFormatSelect,
        templateResult: optionFormatSelect
    });
   if (owner_id !== null) {
        ownerSelect.select2('open');
        ownerSelect.val(owner_id).trigger('change');
    }
    
}

and the below i am calling in my another function to make the option selected:

  populateOwnerSelect(listing.owner_id);

But it only opens the dropdown but it do not make the option selected, please note I’ve added the select2 open trigger to just identify the issue as i was thinking the options are only listed once user opens the dropdown. But it still not making the option selected. Where I am wrong can anyone pelase check the code?

———————–Edited—————————–

after adding console.log() in this:

   processResults: function (data, params) {
                console.log(data);
                return {
                    
                    results: data.results,
                };
            },

i got this output in console:

{results: Array(1)}
results
: 
Array(1)
0
: 
email
: 
""
id
: 
17218
name
: 
" "
phone
: 
"971565266232"
refno
: 
"SP-O-1801"
[[Prototype]]
: 
Object
length
: 
1
[[Prototype]]
: 
Array(0)
[[Prototype]]
: 
Object

and this is my controller code:

public function getList(Request $request)
    {
        $searchTerm = $request->input('q');
        $searchTermId = $request->input('id');
        $query = owners::select('refno', 'id', 'name', 'email', 'phone')->orderBy('name');

        if ($searchTerm) {
            $query->where('name', 'like', '%' . $searchTerm . '%')
                ->orWhere('email', 'like', '%' . $searchTerm . '%')
                ->orWhere('refno', 'like', '%' . $searchTerm . '%')
                ->orWhere('phone', 'like', '%' . $searchTerm . '%');
        }
        if($searchTermId){
            $query->where('id', $searchTermId);
        }

        $owners = $query->limit(100)->get();
        return response()->json(['results' => $owners]);
    }

2

Answers


  1. Assuming that owner_id is a correct value of your select2, try to delete the line ownerSelect.select2('open');

    You can also try $('#owner_id').val(owner_id).trigger('change') at the console of the developer tools using the returned owner_id.

    You can use console.log(owner_id) to see the returned value at the console of the developer tools or,
    you can see it at Network tab of developers tools at Fetch/XHR.

    Login or Signup to reply.
  2. You want to select an option in Select2.

    1. Please ensure no conflicts with the "owner_id" id attribute in your Laravel Blade file or any included or layout files.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search