Reputation: 484
I made a simple file upload where on drag and drop id like to clone 4 inputs fields (filename, alternative texts) foreach, i tried different ways. But the problem is it got cloned much more often than it should.
In my example on Jsfiddle i simulated with 5 files, but it get cloned ~15 times instead of 4 times.
$('button').click(function(){
var lol = 5;
for (var i = 0; i < lol; i++) {
if(i > 0){
var $newCustomer = $('#clonemulti').clone();
$newCustomer.removeAttr('id');
$newCustomer.insertAfter( ".clonemulti" );
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clonemulti" id="clonemulti">
<input type="text" class="filenameauto" name="filename[]" placeholder="" title="Dateiname" maxlength="20" required>
<input type="text" placeholder="Alt. Text (de)" name="alttext[]" maxlength="50" required>
<input type="text" placeholder="Alt. Text (it)" name="alttext[]" maxlength="50" required>
<input type="text" placeholder="Alt. Text (en)" name="alttext[]" maxlength="50" required>
<br/><br/>
</div>
<button>clone</button>
Upvotes: 1
Views: 101
Reputation: 337560
The issue is because .insertAfter(".clonemulti")
is adding the new rows after every existing .clonemulti
element.
To achieve what you require change the selector so you instead insert them after the last instance of that element:
$newCustomer.insertAfter(".clonemulti:last");
Also note that your if (i > 0)
condition is redundant when you can just initialise i
to 1
in the loop. Here's a full example of the updated JS:
$('button').click(function() {
var lol = 5;
for (var i = 1; i < lol; i++) {
var $newCustomer = $('#clonemulti').clone();
$newCustomer.removeAttr('id');
$newCustomer.insertAfter(".clonemulti:last");
}
});
Upvotes: 3