下面的場景你們已經見得多了,假設左側的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