表單需要讓使用者自行增減填寫列時,用 createElement 加 appendChild 新增、用 removeChild 刪除,是最直白的組合。
function addDepartment() {
var x = document.getElementById('department');
var li = document.createElement("li");
li.className = "list_nr_bg";
li.innerHTML = "<span class='nr6'>"
+ "<select name='institute'>"
+ "<c:if test='${baseInstitutes != null}'>"
+ "<c:forEach items='${baseInstitutes}' var='baseInstitute'>"
+ "<option value='${baseInstitute.id}'>${baseInstitute.instituteName}</option>"
+ "</c:forEach></c:if>"
+ "</select></span>"
+ "<span class='nr6'>專業:</span>"
+ "<span class='nr6'><input name='specialty' type='text'></span>"
+ "<span><input type='button' onclick='deleteDepartment(this)' value='刪除'></span>";
x.appendChild(li);
}
function deleteDepartment(obj) {
if (window.confirm("確認刪除嗎?")) {
var li = obj.parentNode.parentNode; // 取得目前列
var ul = li.parentNode; // 取得上層 ul
ul.removeChild(li); // 刪除目前列
} else {
return false;
}
}
<ul id="department">
<li class="list_nr_bg">
<span class="nr6">所屬院系:</span>
<span><input type="button" onclick="addDepartment()" value="增加"></span>
</li>
<li class="list_nr_bg">
<span class="nr6">
<select name="institute">
<c:if test="${baseInstitutes != null}">
<c:forEach items="${baseInstitutes}" var="baseInstitute">
<option value="${baseInstitute.id}">${baseInstitute.instituteName}</option>
</c:forEach>
</c:if>
</select>
</span>
<span class="nr6">專業:</span>
<span class="nr6"><input name="specialty" type="text"></span>
</li>
</ul>
刪除時的關鍵是 obj.parentNode.parentNode:按鈕所在的 span 往上兩層才是 li,再往上才是 ul。這種「從事件源逐層往上找」的寫法很實用,但要注意 DOM 結構一變就會失效,因此結構複雜時改用 closest() 會更穩健。另外,動態產生的表單欄位名稱必須唯一,後端才能正確區分每一列的值。