Question

Here is the JSON

{
 "fields": [
  {
   "id": 2,
   "name": "philosophy",
   "children": [
    {
     "id": 2,
     "name": "ethics",
     "field_id": 2,
     "created_at": "2014-04-07T21:04:48.851Z",
     "updated_at": "2014-04-07T21:04:48.851Z"
    }
   ]
  },
  {
   "id": 1,
   "name": "sociology",
   "children": [
    {
     "id": 1,
     "name": "media",
     "field_id": 1,
     "created_at": "2014-04-07T15:45:49.013Z",
     "updated_at": "2014-04-07T15:45:49.013Z"
    },
    {
     "id": 3,
     "name": "objects",
     "field_id": 1,
     "created_at": "2014-04-08T00:47:23.758Z",
     "updated_at": "2014-04-08T00:47:23.758Z"
    }
   ]
  }
 ]
}

Here is the Jquery I have that currently only loads the names of the parent into the select2 field.

$(document).ready(function() {
  $('#topics').select2({
    minimumInputLength: 1,
    multiple: true,
    tokenSeparators: [" "],
    ajax: {
      url: "/fields.json",
      dataType: "json",
      results: function(data, page) {
        return {
          results: $.map( data.fields, function(fields, i) {
            return { text: fields.name,  }
          } )
        }
      }
    }
  });
});

How can I create what amounts to a select form with optgroups loading via ajax? The above is my failed attempt

Was it helpful?

Solution

Try

results: function (data, page) {
    return {
        results: $.map(data.fields, function (field, i) {
            return {
                text: field.name,
                children: $.map(field.children, function(child){
                    return {
                        id: child.id,
                        text: child.name
                    }
                })
            }
        })
    }
}

Demo: Fiddle

Source: Ticket

OTHER TIPS

A optional choice, can use formatResult to format element, such as:

...
ajax: {
...
  results: function (data, page) {
    return {results: data.fields};
  }
},
formatResult: function(field) {
  return field.name;
}
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top