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:

$("#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.

Can anyone please tell me how to clear the user uploaded images if the limit exceeds or disable the submit button?

2 answers

  • answered 2022-05-07 05:18 Vetos

    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();
    }
    

  • answered 2022-05-07 05:18 Dimitris Papageorgiou

    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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum