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);
});
});
});
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."
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.
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.
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.
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);
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With