I have a pretty speciffic question, I have an input file, every time I add a file a new li
with the file name is added to an existing ul
.
I want to create a function that will validate the file input field, If there are li's
in the ul.file-list
I want to remove the required
attribute and if the ul.file-list
is empty I want to add the required
attr
to the file input field.
I thought checking the length of the li's in the ul, if the length is not equal to 0 than remove the require from the file input, the issue is that the event happens when I click the "add file" button and it is before the file is actually added so for example I have no li's in the ul and I click the "add file" button I will get 0, I want to receive the number of li's after the file is added.
This is the file input field html code:
<div class="row">
<div class="col-md-12 mb-3">
</div>
<div class="col-md-12 mb-3">
<div class="custom-file" id="tz-file">
<label class="custom-file-label" for="tzfile">add file</label>
<ul class="file-list">
<li>
<a href="./uploads/303748891/585943101000100490462no.jpg" target="_blank"> 585943101000100490462no.jpg </a>
<span class="item-file" id="2018-303748891-21317-0" href="21317/0">remove file</span>
</li>
</ul>
<input type="file" class="custom-file-input" id="tzfile" name="tzfile" required="">
</div>
</div>
</div>
This is the jQuery code I have written:
document.onload = whenFileRemoved();
$(document).ready(function(){
$('span.item-file, input[type="file"]').bind("click", whenFileRemoved);
});
function whenFileRemoved(){
var isItemInList = $(this).closest('.row').find('.file-list li').length;
console.log(isItemInList);
if(isItemInList != 0){
$(this).closest('.row').find('input[type=file]').prop('required', false);
}else{
$(this).closest('.row').find('input[type=file]').prop('required', true);
};
};
any help will be great.