JQuery Check Input File

I have file input fields in a group as shown below. I would like all of them to be required.

<!-- file upload group -->
<div class="Fieldset FileUpGroup">
  <span class="Legend">File Upload Group: (required)</span>
  <input name="fileUploads[]" type="file">
  <input name="fileUploads[]" type="file">
  <input name="fileUploads[]" type="file">
</div>

I have the following jQuery to validate, but it only validates the first.

$('.FileUpGroup').each(function() {
    if($(this).find('input[type=file]').val() == '') { 
        Response('- Upload file not selected!', true);
        $(this).addClass('Error').fadeOut().fadeIn();
        return false;
    }
    else {
        $(this).removeClass('Error');
    }
});

Thank!

+5
source share
2 answers

You are using each()in the wrong element:

$('input[type="file"]').each(function() {
    var $this = $(this);
    if ($this.val() == '') { 
        Response('- Upload file not selected!', true);
        $this.addClass('Error').fadeOut().fadeIn();
        return false;
    } else {
        $this.removeClass('Error');
    }
});
+9
source

.val()returns only the first value.
In your loop, ($('.FileUpGroup').each)only one element is activated ... an element DIV.FileUpGroup.
$('.FileUpGroup input[type=file]')will find all the elements and then repeat them one at a time

Here is an example. Hope I have been helpful.

$('.FileUpGroup input[type=file]').each(function() {
    if($(this).val() === '') {
        // wabba dabba do
    }
    else {
        // badda bawwa do
    }
});
0
source

All Articles