I have a problem with duplicating a div and displaying it within it's own parent div. I have several divs with the same duplication button. However, the button only duplicates the div in one of the parent divs. It does not display a div within its own parent div.
In my example I have four buttons. When clicking one of them there should be a div displaying underneath the button you press. However, it only duplicates the div and displays it underneath ONE of the buttons. What am I doing wrong?
https://jsfiddle.net/qer6c5b1/
$(document).ready(function() {
$(".addB").click(function() {
$(".newDiv")
.eq(0)
.clone()
.insertAfter(".newDiv:last")
.show();
});
$(document).on('click', '.addB button[type=submit]', function(e) {
e.preventDefault()
var $frm = $(this).closest('.addB');
console.log($frm.serialize());
$.ajax(
$frm.attr('action'), {
method: $frm.attr('method'),
data: $frm.serialize()
}
);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
CodePudding user response:
The issue is due to your fixed .newDiv:last
selector - this will always target the same element no matter which button is clicked.
To fix this you can determine which button was clicked from the Event that's passed to the event handler and then use DOM traversal to find the related .newDiv
to clone.
jQuery($ => {
$(".addB").click(e => {
let $btn = $(e.target);
$btn.prev('.newDiv').clone().insertBefore($btn).show();
});
});
.newDiv {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<div >
<p>This is the div i need to duplicate #1</p>
</div>
<button > </button>
</div>
<div >
<div >
<p>This is the div i need to duplicate #2</p>
</div>
<button > </button>
</div>
<div >
<div >
<p>This is the div i need to duplicate #3</p>
</div>
<button > </button>
</div>
<div >
<div >
<p>This is the div i need to duplicate #4</p>
</div>
<button > </button>
</div>
Also note that I amended the parentDiv
class to be common amongst all the elements. This is because incremental class
and id
attributes are an anti-pattern and should be avoided.
Finally, this logic assumes that each button is appending different content from within its parent. If the content that's cloned is identical each time, clone a single element and remove the duplicates from the DOM, or use a <template />
to hold the content to be appended.