JQuery 操作select(去重+排序)

下面的场景大家已经见得多了,假设左侧的select id为allMenus,右边的select id为menus

JQuery 操作select(去重+排序)

jquery对select的操作大全可以看这里

简单的移来移去:

$().ready(function() {  
    	$('#add').click(function() {
    	    return !$('#allMenus option:selected').clone().appendTo('#menus');
    	});
        $('#remove').click(function() {  
           return !$('#menus option:selected').remove();  
        });  
    }


如果要加上去重判断,并且自动根据value值排序,那么可以使用grepsort函数,

注释已经很详细,直接贴代码:

$().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的代码如下(备份用,大家可以略过此处):

<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">&lt;--</button>
		
		<sf:select path="menus" multiple="true" size="10" >
			<sf:options items="${menus }" itemLabel="displayName" itemValue="id"/>
		</sf:select>
	</div>
</div>



参考:

http://stackoverflow.com/questions/7570629/using-jquery-to-add-selected-items-from-one-combobox-to-another

http://stackoverflow.com/questions/12712660/jquery-move-item-from-one-select-box-to-another-while-retaining-listing-order

你可能感兴趣的:(jquery,select,move)