下面的场景你们已经见得多了,假设左侧的select id为allMenus,右边的select id为menus html
jquery对select的操做大全能够看这里 jquery
简单的移来移去: app
$().ready(function() { $('#add').click(function() { return !$('#allMenus option:selected').clone().appendTo('#menus'); }); $('#remove').click(function() { return !$('#menus option:selected').remove(); }); }
若是要加上去重判断,而且自动根据value值排序,那么可使用grep
和sort
函数, ide
注释已经很详细,直接贴代码: 函数
$().ready(function() { $('#add').click(function() { // select this once into a variable to minimize re-selecting var $menus = $('#menus'); // clone all selected items var $items = $.grep($('#allMenus option:selected').clone(), function(v){ // if the item does not exist return true which includes it in the new array return $menus.find("option[value='" + $(v).val() + "']").length == 0; }); // append the collection to the destination list $menus.append($items); //part II sort. var $options = $menus.find('option'); // get all options $options = $options.sort(function(a,b){ // sort by value of options return a.value - b.value; }); $menus.html($options); // add new sorted options to select return false; }); $('#remove').click(function() { return !$('#menus option:selected').remove(); }); //automatically select all the menus in right side when submit form. $('#inputForm').submit(function(){ $('#menus option').each(function(i) { $(this).attr("selected", "selected"); }); }); });
JSP的代码以下(备份用,你们能够略过此处): this
<div class="control-group"> <label class="control-label" for="menus">权限:</label> <div class="controls"> <select id="allMenus" name="allMenus" multiple="true" size="10"> <c:forEach items="${allMenus }" var="m"> <option value="${m.id }">${m.displayName }</option> </c:forEach> </select> <button id="add">--></button> <button id="remove"><--</button> <sf:select path="menus" multiple="true" size="10" > <sf:options items="${menus }" itemLabel="displayName" itemValue="id"/> </sf:select> </div> </div>
参考: .net
http://stackoverflow.com/questions/7570629/using-jquery-to-add-selected-items-from-one-combobox-to-another code
http://stackoverflow.com/questions/12712660/jquery-move-item-from-one-select-box-to-another-while-retaining-listing-order orm