For me the real trick was getting all of the options for each optgroup to migrate to their optgroup. Here's the code of a working page for this:
Code:
<!DOCTYPE html>
<html>
<head>
<title>Optgroup - Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function makegroups(id, groups){
var parentselect = document.getElementById(id), opts = parentselect.options,
i = opts.length, j = groups.length, groupobj = {};
while(--j > -1){
groupobj[groups[j]] = [document.createElement('optgroup'), []];
groupobj[groups[j]][0].setAttribute('label', groups[j]);
parentselect.insertBefore(groupobj[groups[j]][0], parentselect.firstChild);
}
while(--i > -1){
j = groups.length;
while(--j > -1){
if(opts[i].value.indexOf(groups[j]) > -1){
groupobj[groups[j]][1].push(opts[i]);
}
}
}
j = groups.length;
while(--j > -1){
i = groupobj[groups[j]][1].length;
while(--i > -1){
groupobj[groups[j]][0].appendChild(groupobj[groups[j]][1][i]);
}
}
}
</script>
</head>
<body>
<select id="vendorCode" name="vendorCode">
<option value="05-South">Chennai</option>
<option value="06-South">Bangalore</option>
<option value="01-North">Delhi</option>
<option value="02-North">Punjab</option>
<option value="03-North">Gujarat</option>
</select>
<script type="text/javascript">
makegroups('vendorCode', ['South', 'North']);
</script>
</body>
</html>
Live Demo:
http://home.comcast.net/~jscheuer1/s...s/optgroup.htm
I also worked out a version where the groups can be determined via regular expression from the option values:
http://home.comcast.net/~jscheuer1/s.../optgroup2.htm
Use your browser's "view source" to get its code if you're interested.
Bookmarks