简体   繁体   English

jquery 文件超过限制如何清除用户上传的图片

[英]How to clear user uploaded images if the limit of files exceeded in jquery

I have a simple form where a user can upload multiple images.我有一个简单的表单,用户可以在其中上传多张图片。 I only want the user to upload 4 images at once, so I did the following:我只希望用户一次上传 4 张图片,所以我做了以下操作:

 $("#myfile").on("change", function() { if ($("#myfile")[0].files.length > 4) { alert("You can select only 4 images"); } });
 <input type="file" id="myfile" class="form-control" name="pimage[]" multiple="multiple">

This gives an alert when the user uploads more than 4 images but doesn't stop them from submitting the form.当用户上传超过 4 张图像但不会阻止他们提交表单时,这会发出警报。

Can anyone please tell me how to clear the user uploaded images if the limit exceeds or disable the submit button?如果超过限制或禁用提交按钮,谁能告诉我如何清除用户上传的图像?

I will implement the disable attribute strategy as I said in the comments:我将按照我在评论中所说的那样实施禁用属性策略:

$("#myfile").on("change", function() {
if ($("#myfile")[0].files.length > 4) {
    alert("You can select only 4 images");
    $(".form-control").prop("disabled",true);
 } 
});

With the above code the user will not be able to submit the form使用上面的代码,用户将无法提交表单

In this case better to create one more variable with flag status and then check it before submit a form.在这种情况下,最好再创建一个带有标志状态的变量,然后在提交表单之前检查它。

Something like that:像这样的东西:

let flag = false;

$("#myfile").on("change", function() {
    if ($("#myfile")[0].files.length > 4) {
        alert("You can select only 4 images");
        flag = true;
    }
});

if(!flag){
    $('#form').submit();
}

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

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