Piter J. Clark
Piter J. Clark

Reputation: 25

Select2 ajax: preselected data in edit mode

I'm making user profile page on Laravel and using select2 component to filter huge list of items.

I have a ajax-based select2. It's good when you are on /create page, but I need to have selected value in it, when I am on page /edit/1.

$('.search-filter-ajax').select2({
                    width: '100%',
                    minimumInputLength: 3,
                    placeholder: "Search...",
                    ajax: {
                        url: '/api/listing/search/',
                        data: function (term) {

                            return {
                                data: term.term
                            };
                        },
                        processResults: function (data) {
                            return {
                                results: $.map(data, function (item) {
                                    return {
                                        text: item.name,
                                        search_from: item.name,
                                        model: 'some_model',
                                        id: item.id
                                    }
                                })
                            };
                        },
                        dataType: 'json',
                        type: "GET",
                        delay: 250,
                    },

                });

I tried to use initSelection function, but no luck, because it creates only select2 text elements, when I need real <option value="1"> something </option> component.

initSelection: function (element, callback) {
            var id = $(element).data('select-id');
            var text = $(element).data('select-text');
            callback({ id: id, text: text });
        },

How can I have a valid preselected option in select2 on page load, but still having opportunity to fire ajax call by onChange?

Upvotes: 1

Views: 948

Answers (1)

Simon Pasku
Simon Pasku

Reputation: 649

well, you could try to use your own logic to generate slect options like

$.ajax().then((res)=>{
  $('#select').html('');
    res.data.forEach((item)={$('#select').append($('option').text(item.text).value(item.value);)})
})

Upvotes: 1

Related Questions