0

I make a div with dynamic elements using JQuery. I can create div elements BUT I can't remove this! How can i solve this problem.

        <div class="row" id="bulk">
    <div class="col-md-3">
      <div class="form-group">
        <label>Color</label>
        <input type="text" name="color" class="form-control">
      </div>

    </div>
    <div class="col-md-3">
      <div class="form-group">
        <label>Quantity</label>
        <input type="text" name="qty" class="form-control">
      </div>
    </div>

    <div class="col-md-3" id="yarn&febric">
      <div class="form-group">
         <label>Ex-Factory Date</label>
        <input id="exfact" type="text" class="form-control" name="exfactdate" placeholder="">
      </div>
    </div>
   </div>

My JQuery Part.

  $(document).ready(function(){

var bulknitdown=$('#bulk').html();
$('.add').click(function(){

        $('#bulk').append(bulknitdown);

});
$('.remove').click(function(){
    bulknitdown.last().remove();
});
});

1 Answers1

2

You have to make clone of HTML code by wrapping div class. Check below code snippet, you will understand easily.

I hope this works for you.

$(document).ready(function(){

var bulknitdown="<div class='row'>"+$('#bulk .row').first().html()+"</div>";
$('.add').click(function(){
     $('#bulk').append(bulknitdown);
     $('#bulk .row').last();   
        
});
$('.remove').click(function(){
    if($('#bulk .row').length>1){
      $('#bulk .row').last().remove();
    }
    else{
      alert("no extra row found for remove");
    }
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bul_container">
<div id="bulk">
<div class="row">
    <div class="col-md-3">
      <div class="form-group">
        <label>Color</label>
        <input type="text" name="color" class="form-control">
      </div>

    </div>
    <div class="col-md-3">
      <div class="form-group">
        <label>Quantity</label>
        <input type="text" name="qty" class="form-control">
      </div>
    </div>

    <div class="col-md-3" id="yarn&febric">
      <div class="form-group">
         <label>Ex-Factory Date</label>
        <input id="exfact" type="text" class="form-control" name="exfactdate" placeholder="">
      </div>
    </div>
   </div>
   </div>
   </div>
   <button id="add_btn" class="add">Add New</button>
   <button id="remove_btn" class="remove">Remove Last</button>
Haresh Vidja
  • 7,750
  • 3
  • 22
  • 40