1. 程式人生 > >用jQuery實現multiple select(列表框)左右新增和刪除功能

用jQuery實現multiple select(列表框)左右新增和刪除功能

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>實現multiple select(列表框)左右新增和刪除功能</title>
		<style>
<!--
select{
text-align:center;
width:300px;
height:150px;
}
-->
</style>
<script type="text/javascript" src="jquery.min.js" ></script> <script type="text/javascript">
<!-- /** *動態的給左邊的下拉列表建立選項 *具體情況可以從資料庫讀取資料動態建立選項 */ $(document).ready(function(){ $("select").attr("multiple", "multiple"); //設定可以多選 for(var i=1;i<=5;i++) { $("#unSelectedServer").append("<option value='"+i+"'>192.168.1.2"+i+"</option>"); } }) //給新增和新增所有按鈕新增onclick事件 $(function(){ $(":button[id^=add]").click(function(){ var toAdds; if($(this).attr("id") == "addAll"){ //新增全部 toAdds = $("#unSelectedServer option"); }else{ //新增選中 toAdds = $("#unSelectedServer option:selected"); if(toAdds.length == 0){ alert("請選擇要新增的伺服器!"); return; } } toAdds.each(function(){ $("#selectedServer").append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option"); $(this).remove(); }); }) }) //給刪除和刪除所有按鈕新增onclick事件 $(function(){ $(":button[id^=delete]").click(function(){ var todeletes; if($(this).attr("id") == "deleteAll"){ //刪除全部 todeletes = $("#selectedServer option"); }else{ //刪除選中 todeletes = $("#selectedServer option:selected"); if(todeletes.length == 0){ alert("請選擇要刪除伺服器!"); return; } } todeletes.each(function(){ $("#unSelectedServer").append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option"); $(this).remove(); }) }) }) // -->
</script>
</head>

<body>
<table width="90%" border="0" cellpadding="0" cellspacing="1" align="center">
<tr>
<td width="40%" align="right">
<select id="unSelectedServer"></select>
</td>
<td align="center" width="20%">
<input type="button" id="add" value=">" />
<br /><br />
<input type="button" id="addAll" value=">>" />
<br /><br />
<input type="button" id="delete" value="<" />
<br/> <br/>
<input type="button" id="deleteAll" value="<<" />
</td>
<td class="black" width="40%">
<select id="selectedServer"></select>
</td>
</tr>
</table>
</bdoy>
</html>