I have a dynamically populated (by ajax) select box with resulting options like that:
You can do this in place using jQuery:
$(document).ready(function() {
var select = $('#destination');
var opt1, opt2;
$('option', select).each(function(i) {
if (i % 2 === 0) {
opt1 = $(this);
} else {
opt2 = $(this);
var label = opt1.text().replace('London-', '');
var optgroup = $('');
optgroup.attr('label', label);
opt2.add(opt1).wrapAll(optgroup);
}
});
});
This code iterates over all the options in the select tag, and wraps every set of two in an optgroup. It also figures out what to label the optgroup as, based on text in the options.