Vis priya Vis priya - 1 year ago 53
jQuery Question

how to show only last add button in the current cloned divs?

i have a code, which will clone the html element, i need to show "add" new button(which will clone the div) only for the bottom most copy. not for all cloned divs.

codepen for this

<div id="duplicater">
<input type="number" class="quantity" id="quantity"/>
<button id="removebutton" class='remove'>Delete</button>
<button id="add">add</button>
<div id="new_item_details" class ="new_item_details">

jQuery(document).ready(function() {
var id = 0;
jQuery(document).on('click', '#add', function(e) {
var button = jQuery('#duplicater').clone();
button.attr('id', 'new_' + id).attr('data-id', id);
button.find('.remove').attr('data-id', id);

jQuery(document).on('click', '.remove', function(e) {
var thisId = jQuery(this).data('id');
jQuery('div[data-id="' + thisId + '"]').remove();


Answer Source

I think a CSS solution here can be much easier. (I wrapped your DIVs in a container).

#duplicater #removebutton {
  display: none;

div.container button.add {
  display: none;
#rows-container div:nth-last-child(2) button.add {
  display: inline-block;

Notice that I used the nth-last-child(2) because you have another DIV after the actual rows with the input elements.

This is your updated codepen: