有些表單需要讓使用者自行決定上傳檔案數,例如成績單、證件照。做法是準備一個「新增」按鈕,點一次就多一列 file 欄位,每列各自帶一個移除按鈕。
<form id="fileForm" action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>
<input type="file" name="file" />
<input type="button" id="addButon" value="Add" onclick="add()" />
</td>
</tr>
</table>
</form>
注意 enctype="multipart/form-data" 是檔案上傳的必要條件,少了它後端收不到檔案。
// 新增一列
function add() {
var content = "<tr><td>";
content += "<input type='file' name='file'>";
content += "<input type='button' value='Remove' onclick='remove(this)'>";
content += "</td></tr>";
$("#fileForm").append(content);
}
// 移除目前所在列
function remove(obj) {
$(obj).parent().parent().remove();
}
function add() {
var $row = $("<tr><td><input type='file' name='file'>" +
"<button type='button' class='del'>Remove</button>" +
"</td></tr>");
$("#fileForm").append($row);
}
// 事件委派,動態產生的元素也能生效
$("#fileForm").on("click", ".del", function () {
$(this).closest("tr").remove();
});
$("#addButon").on("click", add);
closest("tr") 則不受影響。name="file",後端就能以陣列方式一次接收多檔(如 PHP 的 $_FILES['file'] 會是陣列結構)。