Reputation:
I have a jQuery code which will create select
from a ul li menu
. I want to add optgroup
from parent menu, but don't know how to. Here is my code:
// Create the dropdown base
jQuery("<select />").appendTo("#module-menu");
// Create default option "Go to..."
jQuery("<option />", {
"selected": "selected",
"value" : "",
"text" : "Go to..."
}).appendTo("#module-menu select");
// Populate dropdown with menu items
jQuery("#menu a").each(function() {
var el = jQuery(this);
jQuery("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("#module-menu select");
});
jQuery("#module-menu select").change(function() {
window.location = jQuery(this).find("option:selected").val();
});
Upvotes: 3
Views: 1614
Reputation: 24526
$('#parent')
.append($('<select>')
.append($('<optgroup>')
.prop('label', 'group 1')
.append($('<option>')
.text('option 1'))));
Another example taking data from ul. Code:
var sel = $('<select>');
$('#parent').append(sel);
$('#menu>li').each(function()
{
var group = $('<optgroup>')
.prop('label', $(this).find('>span').text());
sel.append(group);
$(this).find('ul>li').each(function()
{
var opt = $('<option>')
.text($(this).find('>span').text());
group.append(opt);
});
});
Upvotes: 3