JSFiddle - React, Tailwind, and code Playground
by TheFiddler
HTML
<table border="0">
<tr>
<td>
<select multiple id="select1" class="w100p">
<optgroup label="Group A">
<option value="1">Option 1a</option>
<option value="2">Option 1b</option>
</optgroup>
<optgroup label="Group 2">
<option value="3">Option 2a</option>
<option value="4">Option 2b</option>
</optgroup>
</select>
</td>
<td width="100" align="center">
<a href="#" id="add">>></a>
<br>
<a href="#" id="remove"><<</a>
</td>
<td>
<select multiple id="select2" class="w100p"></select>
</td>
</tr>
</table>
JavaScript
var $select1 = $('#select1');
$select2 = $('#select2');
$('option').each(function() {
$(this).attr('optgroup', $(this).parent().attr('label'));
});
$('#add').click(function() {
var $el = $('#select1 option:selected'),
groupName = $el.attr('optgroup'),
$parent = $el.parent(),
$optgroup = $select2.find('optgroup[label="' + groupName + '"]');
if (!$el.length) return false;
$el.each(function() {
groupName = $(this).attr('optgroup');
$parent = $(this).parent();
$optgroup = $select2.find('optgroup[label="' + groupName + '"]');
if (!$optgroup.length) $optgroup = $('<optgroup label="' + $(this).attr('optgroup') + '" />').appendTo($select2);
$(this).appendTo($optgroup);
if (!$parent.children().length) $parent.remove();
});
return false;
});
$('#remove').click(function() {
var $el = $('#select2 option:selected'),
groupName = $el.attr('optgroup'),
$parent = $el.parent(),
$optgroup = $select1.find('optgroup[label="' + groupName + '"]');
if (!$el.length) return false;
$el.each(function() {
groupName = $(this).attr('optgroup');
$parent = $(this).parent();
$optgroup = $select1.find('optgroup[label="' + groupName + '"]');
if (!$optgroup.length) $optgroup = $('<optgroup label="' + $(this).attr('optgroup') + '" />').appendTo($select1);
$(this).appendTo($optgroup);
if (!$parent.children().length) $parent.remove();
});
return false;
});
$("select").delegate('optgroup', 'click', function() {
$(this).toggle(function() {
$(this).children().attr("selected", "selected");
}, function() {
$(this).children().attr("selected", false);
});
});