Vis priya Vis priya - 1 month ago 7
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">
<label>Number:</label>
<input type="number" class="quantity" id="quantity"/>
<button id="removebutton" class='remove'>Delete</button>
<button id="add">add</button>
</div>
<div id="new_item_details" class ="new_item_details">
</div>

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

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


});
</script>

Answer

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:
http://codepen.io/anon/pen/bwQzvN