簡體   English   中英

js forms oninput 事件

[英]js forms oninput event

我有一個帶有多個文件字段的表單,每當文件上傳到它時,我 append 將它們添加到一個名為filesinput的數組中(使用 oninput 事件)並將它們添加到一個表中以顯示所有上傳的文件以及一個刪除按鈕文件。 我攔截了提交事件並改為filesinput數組。 但是,每當我單擊“刪除”按鈕時,由於某種原因,表單會自行提交。

這是我的代碼-

window.onload =  function() {
                //var fileinput = document.querySelector('#inputfiles');
                var fileform = document.querySelector('form');
                var filetable = document.querySelector('#submitted');

                fileform.oninput = function(e) {
                    if(!e.target.files)
                        return;
                    var temp = Array.prototype.slice.call(e.target.files);
                    temp.forEach(function(file) {
                        filesinput.push(file);
                        filetable.innerHTML += '<tr> <td>' + file.name + '</td> <td> <button id="' + file.name + '" onclick="removeFile(this.id)">Remove</button></td></tr>';
                    });  
                }

                fileform.addEventListener('submit', function(e) {
                    e.preventDefault();
                    send(filesinput);
                });
            }   

編輯- removeFile功能-

function removeFile(filename) {
                var ind;
                filesinput.forEach(function(file, index) {
                    if(file.name == filename) {
                        ind = index;
                    }
                });
                filesinput.splice(ind, 1);
            }

它在 window.onload function 之外,如果這很重要的話。

請嘗試將<button id="' + file.name + '" onclick="removeFile(this.id)">Remove</button>更改為<button type="button" id="' + file.name + '" onclick="removeFile(this.id)">Remove</button>

按鈕類型不能提交,那么只有點擊刪除按鈕時不會提交表單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM