DIV CSS 佈局教程網

jQuery 動態新增/移除 input type="file" 上傳欄位
編輯:JQuery特效代碼     

有些表單需要讓使用者自行決定上傳檔案數,例如成績單、證件照。做法是準備一個「新增」按鈕,點一次就多一列 file 欄位,每列各自帶一個移除按鈕。

一、HTML 結構

<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" 是檔案上傳的必要條件,少了它後端收不到檔案。

二、jQuery 腳本

// 新增一列
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();
}

三、幾個實務上的建議

  • 不要用 inline onclick:把事件綁定改寫成樣式,語意更清楚也更容易維護:
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 取代 parent().parent():後者一旦巢狀層級改變就會出錯,closest("tr") 則不受影響。
  • 按鈕要指定 type="button":在 form 內若漏寫 type,預設會是 submit,按下去會直接送出表單。
  • 移除後的欄位命名:所有 file 欄位都叫 name="file",後端就能以陣列方式一次接收多檔(如 PHP 的 $_FILES['file'] 會是陣列結構)。
  • 别忘了進безопасность檢查:前端限制檔案類型只是使用者體驗,真正的型別與大小驗證一定要在伺服器端再做一次。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved