sourabh shinde sourabh shinde - 16 days ago 11
jQuery Question

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

HTML :

<form role="form" action="/wohoo" method="POST">
<label>Stuff</label>
<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>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>


Jquery:

$('.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) {
$(this).parent('.multi-field').remove();
}
adjustButtonVisiblity();
});

adjustButtonVisiblity();
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

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: http://jsbin.com/wegenuveza/edit?html,js,output

Comments