6

I have file input fields in a group like below. I'd like all of them to be required fields.

<!-- 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 one.

$('.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 You!

2 Answers 2

11

You're using each() on 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');
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

.val() only returns the first value.
In your loop ($('.FileUpGroup').each) is only activated for one item... the DIV.FileUpGroup element.
$('.FileUpGroup input[type=file]') will find all the items and then iterates them one at a time
Here is an example. Hope I have been useful.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.