動態增減表格的資料列,是表單設計中很實用的技巧,例如動態填寫多位聯絡人。本文示範如何用 jQuery 輕鬆做到「新增一列」與「刪除一列」,並附上防呆設計。
點擊「新增一行」時,複製表格的第一列並附加到最後,同時清空新列的輸入欄位;點擊「刪除」時,會先確認是否真的要刪,並限制至少保留一列,避免整張表被清空。
<html>
<head>
<title>新增、刪除一行</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../js/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(function() {
$("#addOneRow").click(function() {
var tempTr = $("tr:first").clone(true);
$("tr:last").after(tempTr);
$("tr:last > td > #name").val(""); // 新列 name 清空
$("tr:last > td > #address").val(""); // 新列 address 清空
});
$(".delOneRow").click(function() {
if ($("tr").length < 2) {
alert("至少保留一行!");
} else {
if (confirm("確認刪除?")) {
$(this).parent().parent().remove();
}\br /> }
});
});
</script>
</head>
<body>
<table border="1">
<tr>
<td>姓名:</td>
<td><input type="text" id="name" name="name" /></td>
<td>地址:</td>
<td><input type="text" id="address" name="address" /></td>
<td><input type="button" class="delOneRow" value="刪除" /></td>
</tr>
</table>
<input type="button" id="addOneRow" value="新增一行" />
</body>
</html>
幾個值得注意的細節:clone(true) 的參數 true 表示連事件一起複製;刪除時用 $(this).parent().parent() 從按鈕回溯到整個 tr 再移除;而 length < 2 的判斷則確保不會把最後一列也刪掉。這些小防呆能讓表單更貼心、更不易出錯。