Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create html select with optgroup from json

I have a JSON string (from php json_encode) that looks like;

var json = [{"Foo":[{"id":1,"name":"aaa"},{"id":2,"name":"bbb"}]},{"Bar":[{"id":3,"name":"ccc"},{"id":4,"name":"ddd"}]}];

I want to be able to create an html select using Javascript/jQuery in the form;

<select>
    <optgroup label="Foo">
        <option value="1">aaa</option>
        <option value="2">bbb</option>
    </optgroup>
    <optgroup label="Bar">
        <option value="3">ccc</option>
        <option value="4">ddd</option>
    </optgroup>
</select>

In terms of processing the json I get this far (not far I know), but jsFiddle fails to run it and freezes my browser.

var json = [{"Foo":[{"id":1,"name":"aaa"},{"id":2,"name":"bbb"}]},{"Bar":[{"id":3,"name":"ccc"},{"id":4,"name":"ddd"}]}];

$.each(json, function(i,group) {
    console.log(i);
    $.each(group, function(j, option) {
        console.log(j, option);
        $.each(option, function(k, item) {
            console.log(k, item);
        });
    });
});​
like image 602
Rooneyl Avatar asked Dec 19 '12 16:12

Rooneyl


People also ask

Can Optgroup be selected?

From Select2 docs: "Furthermore, <optgroup> elements cannot be made selectable. This is a limitation of the HTML specification and is not a limitation that Select2 can overcome."

How do I use Optgroup tags?

The <optgroup> tag is used to group related options in a <select> element (drop-down list). If you have a long list of options, groups of related options are easier to handle for a user.

How do you select a group in HTML?

In HTML, the select element is used to create both multi-select lists and combo boxes. The various allowed options are each indicated with option elements. To group options together, use the optgroup element, with the related option elements inside that element.

How do you style an Optgroup?

optgroup { font-style: normal|italic|oblique; } styles the optgroup label and options within the optgroup. option { font-style: normal|italic|oblique; } has no effect. select { font-weight: normal; } has no effect but select { font-weight: bold; } will make all options in the select box bold.


1 Answers

This should run just fine.

var $select = $("<select>");
$select.appendTo("#somewhere");

$.each(json, function(i, optgroups) {
    $.each(optgroups, function(groupName, options) {
        var $optgroup = $("<optgroup>", {label: groupName});
        $optgroup.appendTo($select);

        $.each(options, function(j, option) {
            var $option = $("<option>", {text: option.name, value: option.id});
            $option.appendTo($optgroup);
        });
    });
});
like image 79
Tomalak Avatar answered Oct 17 '22 23:10

Tomalak