Arthur Tarasov Arthur Tarasov - 7 months ago 11
Javascript Question

Dynamically adding input fields with a button, without remove button on the only field

I am trying to use the code from this jsfiddle to dynamically load more fields into the form:

$('.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).click(function() {
if ($('.multi-field', $wrapper).length > 1)
$(this).parent('.multi-field').remove();
});
});


Everything works great, but the problem is that the "remove" button stays there when there is only one field.

I want to make it look like this when there is only one field. The javascript uses
clone
function. If I remove the remove button, it gets removed from all the subsequent "clones" when more fields are added. I am very new to javascript. Does anyone have an advice on how to remove the "remove" button when there is only one field instance?

Answer

Check out this simple solution which doesn't remove the button but adjusts visibility. Depending on your application, that might be enough:

http://jsfiddle.net/hMJEy/1933/

$('.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();
        }
    }
});