Reputation: 285
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!
Upvotes: 6
Views: 23489
Reputation: 462
.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
}
});
Upvotes: 0
Reputation: 77956
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');
}
});
Upvotes: 11