Fill in Select with optiongroup

1

I want to create a multiple select like this

WhatIwasabletodowasthis

What I want is to group all the records of the same group, as organized in the plugin

See the code here

My json returns this

    
asked by anonymous 24.05.2015 / 05:32

1 answer

1

The part of AJAX you have to be doing because I can not test, but inside AJAX you receive a JSON already converted into an object. Then, in this function done you can use this way:

var grupos = {};
json.forEach(function (data) {

    var grupo = data.nome1;
    if (!grupos[grupo]) {
        var optG = document.createElement('optgroup');
        optG.label = data.nome1;
        select.appendChild(optG);
        var g = {
            data: [],
            el: optG
        }
        grupos[grupo] = g;
        g.data.push(data);
    }
    var option = document.createElement('option');
    option.value = data.id;
    option.innerHTML = data.nome;
    grupos[grupo].el.appendChild(option);
});


$("select").multipleSelect({
    multiple: true,
    multipleWidth: 200,
    width: '100%'
});

What this code does is create an object ordered by groups. As you create / iterate these elements of the array that you receive from the server, you add content to the page. When a new group appears (here: if (!grupos[grupo]) { ) then it creates new optgroup and joins option ali.

Example: link

    
24.05.2015 / 07:18