Nivedit Majumdar
Nivedit Majumdar

Reputation: 67

Set data of a Multiple Select2 element through javascript

I'm loading multiple values into a Select2 element through Javascript, ajax and jquery. While the data is loading properly and can be accessed once loaded, I'm unable to set stored data in the Select2 element.

Edit: I'm using Select2 v3.5.

My code:

HTML:

<input class="jsData" style="width: 100%"  id="select2Data"></input>

Javascript:

 $(".jsData").select2({
                        ajax: {
                            minimumInputLength: 4,
                            contentType: 'application/json',
                            url: '<%=Url.Action("GetData","Controller")%>',
                            type: 'POST',
                            dataType: 'json',
                            data: function (term) {
                                return {
                                    sSearchTerm: term
                                };
                            },
                            results: function (data) {
                                return {
                                    results: $.map(JSON.parse(data), function (item) {
                                        return {
                                            text: item.term,
                                            slug: item.slug,
                                            id: item.Id
                                        }
                                    })
                                };
                            }
                        },
                        multiple: true
                    });

So, this creates a Select2 element where I can traverse to and from a database and load data depending on what I've typed. I can also access the data (entered by the user) using the following line:

$('.jsData').select2('val')

The above line returns an array, which I can store in the database. My current objective is to set the stored data back into the Select2 element. Any help in this matter would be most welcome.

Update: A relevant link for what I want to accomplish: https://select2.github.io/examples.html#programmatic

I want the example of setting multiple elements in Select2. However, the difference would be in the fact that the example in the Select2 documentation brings data at the time of loading the page, while I will be making trips to fetch the data.

Upvotes: 1

Views: 1008

Answers (1)

Brett DeWoody
Brett DeWoody

Reputation: 62871

The Select2 v3.5.4 docs are a bit confusing around this. I think there's a typo in the docs that's misleading.

First, notice that when I retrieve the data from the remote source I'm returning it as an object in the format of {id: ##, name: NAME}.

The first step is to add the initSelection parameter and pass the function to retrieve the previously selected items.

The next step, where I believe there's a typo, is to define the formatSelection parameter (not the formatResult it states in the docs). This function defines how the previously selected result is displayed. In this case I'm merely showing the name property of the result.

The formatResult parameter defines how newly selected options are displayed. You'll notice formatResult and formatSelection are the same below. I could have reused a single function but felt this was better for demonstration.

$(document).ready(function() {
  function formatResult(data) {
    return data.name;
  };

  function formatSelection(data) {
    return data.name; 
  }

  $(".jsData").select2({
    ajax: {
      minimumInputLength: 4,
      url: "https://jsonplaceholder.typicode.com/users",
      type: "GET",
      dataType: "json",
      results: function(data) {
        return {
          results: $.map(data, function(user) {
            return {
              name: user.name,
              id: user.id
            };
          })
        };
      }
    },
    initSelection: function(element, callback) {
      var id = $(element).val();
      if (id !== "") {
        $.ajax("https://jsonplaceholder.typicode.com/users/" + id, {
          dataType: "json"
        }).done(function(data) {
          callback(data);
        });
      }
    },
    formatResult: formatResult,
    formatSelection: formatSelection,
    multiple: true
  });
});

Here's the full working example:

$(document).ready(function() {
  function formatResult(data) {
    return data.name;
  };
  
  function formatSelection(data) {
    return data.name; 
  }

  $(".jsData").select2({
    ajax: {
      minimumInputLength: 4,
      url: "https://jsonplaceholder.typicode.com/users",
      type: "GET",
      dataType: "json",
      results: function(data) {
        return {
          results: $.map(data, function(user) {
            return {
              name: user.name,
              id: user.id
            };
          })
        };
      }
    },
    initSelection: function(element, callback) {
      var id = $(element).val();
      if (id !== "") {
        $.ajax("https://jsonplaceholder.typicode.com/users/" + id, {
          dataType: "json"
        }).done(function(data) {
          callback(data);
        });
      }
    },
    formatResult: formatResult,
    formatSelection: formatSelection,
    multiple: true
  });
});
.jsData {
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css" rel="stylesheet"/>

<input class="jsData" style="width: 100%"  id="select2Data" value="10"></input>

Upvotes: 2

Related Questions