Copying options and optiongroups with jQuery -
i have found great jquery snippet allows copying of option 1 selector , back.
i modify add option groups , when options moved 1 side another, have option group removed empty group , add full group in new selector.
can accomplished using jquery?
html:
<select multiple id="select1" class="w100p"> <optgroup label="group 1"> <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> <a href="#" id="add">add >></a> <br> <a href="#" id="remove"><< remove</a> <select multiple id="select2" class="w100p"></select>
javascript:
$('#add').click(function() { return !$('#select1 option:selected').remove().appendto('#select2'); }); $('#remove').click(function() { return !$('#select2 option:selected').remove().appendto('#select1'); });
although not perfect, should started:
var $select1 = $('#select1'); $select2 = $('#select2'); $('option').each(function(){ $(this).data('optgroup', $(this).parent().attr('label')); }); $('#add').click(function() { var $el = $('#select1 option:selected'), groupname = $el.data('optgroup'), $parent = $el.parent(), $optgroup = $select2.find('optgroup[label="' + groupname + '"]'); if ( ! $el.length ) return false; if ( ! $optgroup.length ) $optgroup = $('<optgroup label="' + $el.data('optgroup') + '" />').appendto($select2); $el.appendto( $optgroup ); if ( ! $parent.children().length ) $parent.remove(); return false; }); $('#remove').click(function() { var $el = $('#select2 option:selected'), groupname = $el.data('optgroup'), $parent = $el.parent(), $optgroup = $select1.find('optgroup[label="' + groupname + '"]'); if ( ! $el.length ) return false; if ( ! $optgroup.length ) $optgroup = $('<optgroup label="' + $el.data('optgroup') + '" />').appendto($select1); $el.appendto( $optgroup ); if ( ! $parent.children().length ) $parent.remove(); return false; });
like said, needs additional work (like consolidating 2 functions; they're doing same thing), should started.
finally, here's fiddle: http://jsfiddle.net/m97zr/3/
Comments
Post a Comment