VibuntuNew
VibuntuNew

Reputation: 23

Cannot clone input fields from third time onwards in jQuery

I need to clone html inputs without values. I tried as below:

$(function() {
        var unique_id = 0;
        $('.click').on('click', function() {
            unique_id++;

            $('#parentSection').clone().insertAfter('#parentSection')
                .find("input, select")
                .val('')
                .each(function(){
                    $(this).attr("id",$(this).attr("id")+"_"+(unique_id));
                    $(this).attr("name",$(this).attr("name")+"_"+(unique_id));
                    var fieldName = $(this).attr('name');
                    $(this).siblings().attr('for', fieldName);
                })
        });
    });
<div id="parentSection">
   <div class="control-group">
            <label for="order">Order</label>
            <input name="order" id="order" type="text">
    </div>
    <div class="control-group">
        <button type="button" class="click">Add</button>
    </div>
</div>

But when I clicked the add button for third time, it will not clone and not even execute this function without generating any errors. So where could I get wrong and how should I correct it?

Upvotes: 1

Views: 87

Answers (1)

Shivendra Singh
Shivendra Singh

Reputation: 3006

Add the form elements like input, select field within row under parentSection, after click on add more get the clone of first row and append to end of div 'parentSection'.

like.

jQuery(function($){
var unique_id = 1;
	jQuery('.click').on('click', function(){
		$("#parentSection .row:first").clone().find("input,select").each(function() {

		/*In this case, Generally for name attr used in array format like - input[0][name1], input[1][name2] etc
		for array you can use like.
		this.name = this.name.replace(/\[(\d+)\]/,function(str,p1){return '[' + (parseInt(p1,10)+unique_id) + ']'});
		*/

		this.name = $(this).attr("name")+"_"+unique_id; //make name unique of new row
		this.id = $(this).attr("id")+"_"+unique_id; // make id unique of new row
		this.value = '';  //male value empty of new row
		}).end().appendTo("#parentSection").find('.delete_row').show();

		unique_id++;


		//Delete current row on click of delete_row button
		jQuery('.delete_row').click(function(e){
		e.preventDefault();
		jQuery(this).parent().remove();

		});

	});
});

 
 

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  

  <div id="parentSection">
   <div class="control-group row">
            <label for="order">Order</label>
            <input name="order" id="order" type="text">
			<a class="delete_row" style="display:none">Delete Row </a>
    </div>
    <div class="control-group">
        <button type="button" class="click">Add</button>
    </div>
</div>

Upvotes: 1

Related Questions