Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
                }
            ]
        }
    ]
}
like image 808
hg8 Avatar asked Aug 04 '16 09:08

hg8


1 Answers

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"

like image 121
Thomas Mairé Avatar answered Oct 04 '22 03:10

Thomas Mairé