简体   繁体   English

如何清除HTML多文件上传而无需刷新页面

[英]How to clear HTML multiple file upload without page refresh

I am trying to count how many files have been uploaded, if over 10 images are uploaded then clear the input field but keep everything else in the form. 我正在尝试计算已经上传了多少文件,如果上传了超过10张图像,请清除输入字段,但将其他所有内容保留在表格中。

Everything works great, used the answer from here to clear input and made a function to count files. 一切正常,使用此处的答案清除输入,并提供了对文件计数的功能。

The issue is if there are more than 10 images uploaded it clears all input fields because the script refreshes the page and all input information is reset. 问题是,如果上传的图像超过10张,它将清除所有输入字段,因为脚本会刷新页面,并且所有输入信息都会重置。 I'm looking to only clear the multiple upload input field and not have the page refresh when that happens. 我希望仅清除多个上传输入字段,并且在这种情况下不刷新页面。

Heres what it looks like so far. 这是到目前为止的样子。

<div class="form-group">
    <label for="post_gallery_img">Gallery Images</label>
    <input id="galleryImgs" type="file" multiple="multiple" name="files[]"><button style="display: none;" onclick="reset2($('#galleryImgs'));event.preventDefault()"></button>
</div>

And the Jquery: 和jQuery:

<script>
  $("#galleryImgs").on("change", function() {
    if($("#galleryImgs")[0].files.length < 11) {
        window.reset2 = function (e) {
            e.wrap('<form>').closest('form').get(0).reset();
            e.unwrap();
        }
    } else {
        $("#addPostsForm").submit();
    }
});
</script>

I am thinking I am going to have to use AJAX, but quite new to it. 我以为我将不得不使用AJAX,但它还很新。

Any help is appreciated. 任何帮助表示赞赏。

You may try something like: 您可以尝试以下方法:

HTML: HTML:

<form id="addPostsForm">
<div class="form-group">
    <label for="post_gallery_img">Gallery Images</label>
    <input id="galleryImgs" type="file" multiple="multiple" name="files[]"><button style="display: none;" onclick="reset2($('#galleryImgs'));event.preventDefault()"></button>
</div>
<br>
<!--<input type="reset" value="Reset">-->
</form>

JS: JS:

$("#galleryImgs").on("change", function() {
    if($("#galleryImgs")[0].files.length < 11) {
        alert("Now reset file input");
        //This code line resets the file input
        $('#galleryImgs').val("");
        alert("The file input has now been reset");
    } else {
        $("#addPostsForm").submit();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM