sourabh shinde sourabh shinde - 1 year ago 110
jQuery Question

Remove button only on recently added input field using clone()


<form role="form" action="/wohoo" method="POST">
<div class="multi-field-wrapper">
<div class="multi-fields">
<div class="multi-field">
<input type="text" name="stuff[]">
<button type="button" class="remove-field">Remove</button>
<button type="button" class="add-field">Add field</button>


$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).click(function(e) {
$('.multi-field:first-child', wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
$('.multi-field .remove-field', $wrapper).show();
$('.multi-field .remove-field', $wrapper).click(function() {
if ($('.multi-field', $wrapper).length > 1) {

function adjustButtonVisiblity() {
if ($('.multi-field', $wrapper).length == 1) {
$('.multi-field .remove-field', $wrapper).hide();

I have html page which contains an div with input field. The div also contains an add button which clones the current input field and append it to the div so that i can have as many input fields as per user needs. I am also having a remove button next to the input field but the problem is i only need remove button on the last added input field to the div.
Any help is appreciated.

Answer Source

On adding and removing a field you can check how many fields there are actually (like you already do it in adjustButtonVisiblity). If you have more than one field, you can show the last remove button.

    function adjustButtonVisiblity() {
            $('.multi-field .remove-field').hide();
            if ($('.multi-field').length > 1)
              $('.multi-field:last-child .remove-field').show();


Now you should call this function also an adding a button.

Here is a working sample on JS Bin:,js,output

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download