Fill in Select with optiongroup

Asked

Viewed 142 times

1

I intend to create a multiple select like that

Esse é o plugin multiple select

What I managed to do was this

Esse foi o que fiz usando json para preencher dinamicamente

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

See the code here

My json returns this este array de objecto

  • Hi Sam, I didn’t quite understand which part is giving problems. You have a JSON and want to mount the select with this data? where is the information of the groups in JSON? is the nome1?

  • yes the group is name1. i wanted to organize by group(name1).

  • Okay, you can give me that JSON or part of it in a jsFiddle so I don’t have to write by hand?

  • yes I can. http://jsfiddle.net/elonesampaio/extbomx2/

  • I think you put the same fiddle in both ^

  • sorry, this is http://wenzhixin.net.cn/p/multiple-select/docs/

Show 2 more comments

1 answer

1


The AJAX part you have to do because I can’t test, but inside AJAX you get a JSON already converted to object. There, in this function done you can use it like this:

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 you receive from the server, you add content to the page. When a new group appears (here: if (!grupos[grupo]) {) then he creates new optgroup and joins the option there.

Example: http://jsfiddle.net/cz89rtou/

  • 1

    Thanks! That’s just what I needed. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.