JQuery 操作select(去重+排序)

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

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

转载于:https://my.oschina.net/uniquejava/blog/86981

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值