Also you need to update the id after removing one element. like if you
have 3 divs then input value ids will be like something_0, something_1, something_2.
Now if you remove the 2nd one then you will have 2 divs with input ids like
something_0 and something_2 and then if you click add again it will add
a 3rd div and input id will something_2
So after removing a div you need to update the id and name accordingly.
Here is complete script
- $(function(){
-
- var
max_fields = 10; //maximum input boxes allowed
- var
$wrapper = $(".input_fields_wrap"); //Fields wrapper
- var
$add_button = $(".add_field_button"); //Add button ID
- var
prefix1 = 'anything';
- var
prefix2 = 'anything_else';
- $add_button.click(function(e){
//on add input button click
-
var count = $wrapper.find('.col-xs-12').length;
- e.preventDefault();
-
if(count < max_fields){ //max input box allowed
-
$wrapper.append('<div class="col-xs-12"><div class="row">\
-
<div class="col-xs-9"><div
class="form-group"><label>Postage Description:</label>\
-
<input type="text" class="form-control"
name="'+prefix1+'_'+count+'"
id="'+prefix1+'_'+count+'"
value=""/></div><!-- form-group --></div>\
-
<!-- col-xs-9 --><div class="col-xs-2"><div
class="form-group"><label>Postage Price:</label>\
-
<input type="text" class="form-control"
name="'+prefix2+'_'+count+'"
id="'+prefix2+'_'+count+'"
value=""/></div><!-- form-group --></div>\
-
<!-- col-xs-2 --><div
class="remove_field"><span class="glyphicon glyphicon-remove">Remove</span><div></div>\
-
<!-- row --></div><!-- col-xs-12 -->'); //add
input box
- }
- });
- $wrapper.on("click",".remove_field",
function(e){ //user click on remove text
-
$(this).parents('.col-xs-12').remove();
- $wrapper.find('.col-xs-12').each(function(i){
-
$(this).find('input[type="text"]:first').attr({"id":
prefix1+'_'+i, "name":prefix1+'_'+i});
-
$(this).find('input[type="text"]:last').attr({"id":
prefix2+'_'+i, "name":prefix2+'_'+i});
- });
- });
- });
See it here http://jsfiddle.net/n6jw8gx9/