I want when the user selects a file to create additional input for file, but if one of the created input fields is empty to not create a new one
Html:
<div class="pickerColors">
<div class="color"><input class="selectFile" id="sortpicture" type="file" name="sortpic" />
</div>
</div>
JS:
function test(){
var totalFields = $('.selectFile').length;
for(i=0;i<totalFields;i++){
if($('.selectFile').eq(i).val()==""){
return false;
}
}
}
$('body').on('change', '.selectFile', function () {
var parent = $(this).parent().attr("id");
test();
if(test() != false){
$('#'+parent).append('<input class="selectFile" id="sortpicture" type="file" name="sortpic" />');
}
});
Found a solution
function isEveryInputEmpty() {
var notEmpty = true;
$('.newImage').each(function() {
if ($(this).val() == '') {
notEmpty = false;
return false; // we've found a non-empty one, so stop iterating
}
});
return notEmpty;
}
$('body').on('change', '.newImage', function () {
var parent = $(this).parent().attr("id");
if(isEveryInputEmpty() == true){
$('#'+parent).append('<input class="newImage" id="sortpicture" type="file" name="sortpic" />');
}
});
There's a few things:
[]
to the end of the nameArray.prototype.some
method document.querySelector('body').addEventListener('change', function(e) { let tgt = e.target if (tgt.classList.contains('selectFile')) { let container = tgt.closest('.color') if (.isEmptyInputAvailable()) { const div = document.createElement('div') div.innerHTML = '<input class="selectFile sortpicture" type="file" name="sortpic[]" />' container.append(div) } } }) function isEmptyInputAvailable() { let inputs = document.querySelectorAll('.sortpicture') return Array.from(inputs).some(input => input.value == '') }
<div class="pickerColors"> <div class="color"><input class="selectFile sortpicture" type="file" name="sortpic[]" /> </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.