当前位置: 代码迷 >> JavaScript >> 左面添加项到右边的JS实现
  详细解决方案

左面添加项到右边的JS实现

热度:305   发布时间:2012-12-20 09:53:21.0
左边添加项到右边的JS实现

1.

总结:

select中设置属性multiple="true"可以出现如下左图的效果,全部项都显示!
?


<table cellspacing="1" cellpadding="3" width="100%">
<tr>
<td width="19%" height="77" align="left" >
???? <select name="brandlist" id="brand_sel" multiple="true">
?????????? <option value="1">爱慕</option>
?????????? <option value="2">GAINREEL</option>
?????????? <option value="3">优品生活</option>
?????????? <option value="4">猫人</option>
??????????? <option value="5">七匹狼</option>
?????????? <option value="6">百丽</option>
?????????? <option value="7">Tata</option>
????? </select>

<td width="13%" align="center" >
? <input type="button" class="button" value=" -> " onclick="javascript:rightMove();"/><br/>
? <input type="button" class="button" value=" <- " onclick="javascript:leftMove();"/><br/>
? <input type="button" class="button" value=" 重置 " onclick="javascript:clean();"/>
</td>
<td width="68%" height="77" align="left" >
??? <select id="choose_sel" multiple="true">
?????????? <option value="5">七匹狼</option>
??? </select>
</td></tr>
</table>

?具体实现代码如下:

?????????? javascript:new Option(text, value)

?????????? 一般用在动态生成选择项目

思想:

往右加:遍历左边,当它被选中时,使用new Option(text,value)创建一个新的option,将其添加到右边,右边长度每次加1,可将长度作为右边select的下标

choose_sel.options[s++]

右边去除:判断右边选中之后,删除即可


获取select长度:$("#id").options.length

判断选中:brand_options[ i ].selected

?

function rightMove(){
 
	var brand_sel = document.getElementById("brand_sel");
	var choose_sel = document.getElementById("choose_sel");
	
	var brand_options = brand_sel.options;
	var s = choose_sel.options.length;
	for(var i=0;i<brand_options.length;i++){
		var is_selected = brand_options[i].selected;
		if(is_selected){
			 var option  = new Option(brand_options[i].text  ,brand_options[i].value); 
			 if(!contains(choose_sel,option)){
				choose_sel.options[s++] = new Option(brand_options[i].text  ,brand_options[i].value); 
			}
		}
	}
}
?
function leftMove(){
	$("#choose_sel>option").each(function(){
		var option= $(this);
		if(option.attr("selected")){
			option.remove();
		}
	});
}
?
function clean(){
 
	$("#choose_sel>option").each(function(){
		 $(this).remove();
	});
	
}
 
function selectChoose(){
	$("#choose_sel>option").attr("selected","true");
	return true;
}
?
function  contains(obj_sel,option){
	var options = obj_sel.options;
	for(var i=0;i<options.length;i++){
		if(options[i].value == option.value){
			return true;
		}
	}
	
	return false;
}

?11

  相关解决方案