skip to Main Content

I have Multiple Value Select2 Which have options generated from MySQL using inline PHP when we submit the form the select2 is encoded into json_encode ["43", "23", "32"] What I want is when user want to edit I make a follow as the user clicks on the button and ajax call is sent to MySQL and in response, we get all values and what I need is show json_encoded array into Select2, it works fine with single value but not working with multiple
If the value is single value its work but in my case its json_array

$(".select2Custom").select2({theme: 'bootstrap4'}).val(data.product_id).trigger('change');

The Result which I Get
The Result I want

2

Answers


  1. Chosen as BEST ANSWER

    Thanks, @Arman Your Solution is Not Giving Me 100% Solution But Give Me the Vision to Solve My Problem like your hint to convert the array into Select2 acceptable Array :) Here is Solution

    I Got JSON_ENCODED Array From Ajax Response ["33", "44", "23"] What I Need is to Show those Options which have id in an array

    and here is Solution

    //I Just Convert Ajax Response into proper JSON and its Works

    var data_array = $.parseJSON(data.product_id);                    
    $(".select2Custom").select2({theme:"classic"}).val(data_array).trigger('change');
    

  2. You should make same format json as the select2 accepts like:

    {"id": "1","text": "some text"}
    

    So convert your initial json with this method:

    processResults: function (data) {
            return {
                results: $.map(data, function(obj) {
                    return { id: obj.mysql_json_id, text: obj.any_text_you_want_display };
                })
            };
        }
    

    check this fiddle
    Edit: Changed fiddle so we select2 can render this array ["32", "44", "40"]

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search