hg8 hg8 - 4 months ago 14
Ajax Question

Select2 optgroup group on JSON/Ajax format request

Using Select2 with JSON/Ajax call, I am trying to create group like this :

<optgroup label="Property Reference">
<option value="1">5742</option>
<option value="2">5788</option>
<option value="3">5762</option>
<option value="4">5711</option>
</optgroup>


The documentation for my issue is not available.




The format I managed to get to work :

{
results: [
{
id: 'CA',
text: 'California'
},
{
id: 'CO',
text: 'Colarado'
]
}
}


But there is no group here.

Following this question, I tried the following format :

{
"results": {
"text": "Mountain Time Zone",
"children": [
{
"id": "CA",
"text": "California"
},
{
"id": "CO",
"text": "Colorado"
}
]
}
}


and

{
"results": {
"Mountain Time Zone": [
{
"id": "CA",
"text": "California"
},
{
"id": "CO",
"text": "Colorado"
}
]
}
}


and

{
"Mountain Time Zone": [
{
"id": "CA",
"text": "California"
},
{
"id": "CO",
"text": "Colorado"
}
]
}


But none are working. Anyone know what the correct format is ?

You can test it here : https://jsfiddle.net/5am4zda6/2/

EDIT Solved: Damn... Forgot
[]
.
Correct format is :

{
"results": [
{
"text": "Mountain Time Zone",
"children": [
{
"id": "CA",
"text": "California"
},
{
"id": "CO",
"text": "Colarado"
}
]
}
]
}

Answer

Try like this:

{
    "results": [
        {
            "text": "Groupe 1",
            "children": [
                {
                    "id": "CA",
                    "text": "California"
                },
                {
                    "id": "CO",
                    "text": "Colarado"
                }
            ]
        },
        {
            "text": "Groupe 2",
            "children": [
                {
                    "id": "CA",
                    "text": "California"
                },
                {
                    "id": "CO",
                    "text": "Colarado"
                }
            ]
        }
    ]
}

I think you have forgot [ juste after "results"

Comments