Snippets › Add and Remove Fields Dynamic and Simple with jQuery

This is another example of the previous post about dynamically adding and removing of input fields. It's similar in function but we don't use x as field counts, here we just directly access the childNodes inside the wrapper element and accomplish the same goal.

The jQuery:

var max_fields      = 10;
var wrapper         = $(".input_fields_wrap"); 
var add_button      = $(".add_field_button");
var remove_button   = $(".remove_field_button");

$(add_button).click(function(e){
    e.preventDefault();
    var total_fields = wrapper[0].childNodes.length;
    if(total_fields < max_fields){
        $(wrapper).append('<input type="text" name="answer[]" class="field-long" />');
    }
});
$(remove_button).click(function(e){
    e.preventDefault();
    var total_fields = wrapper[0].childNodes.length;
    if(total_fields>1){
        wrapper[0].childNodes[total_fields-1].remove();
    }
});

The HTML

<button type="button" class="add_field_button">Add Field</button>
<button type="button" class="remove_field_button">Remove Field</button>
<div class="input_fields_wrap">
<input type="text" name="answer[]" class="field-long" />
<input type="text" name="answer[]" class="field-long" />
<input type="text" name="answer[]" class="field-long" />
</div>

Demo :

1 Comment Add Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.