Select2: how to set data after init?

后端 未结 7 1871
醉梦人生
醉梦人生 2021-02-06 22:33

I need to set an array of data after initializing select2. So I want to make something like this:

var select = $(\'#select\').select2({});
select.data([
  {id: 1         


        
相关标签:
7条回答
  • 2021-02-06 23:07

    I've recently had the scenario where changing one select2 object alters the contents of a second (parent - child groupings effectively). I used an ajax call to retrieve a new set of Json data, which was then picked up by the second select2 object. I've included the code below:

     $("#group").on('change', function () {
            var uri = "/Url/RetrieveNewResults";
            $.ajax({
                url: uri,
                data: {
                    format: 'json',
                    Id: $("#group :selected").val()
                },
                type: "POST",
                success: function (data) {
                    $("#groupchild").html('');
                    $("#groupchild").select2({
                        data: data,
                        theme: 'bootstrap',
                        placeholder: "Select a Type"
                    });
                },
                error: function () {
                    console.log("Error")
                }
            });
        });
    

    I found that I had to include the $("#groupchild").html('') in order to clear out the previous set of data in the second select2. Hope this helps.

    0 讨论(0)
提交回复
热议问题